更新时间:2023-11-04 21:33:10
如果文件中的名字与mainvoter
不匹配,则返回false
.代码中的注释以及建议的更改:
You return false
if the first name in the file does not match mainvoter
. Comments in code with the suggested changes:
bool searchname(const std::string& mainvoter) // const& instead of copying the string.
{ // It's not strictly needed, but is often
// more effective.
std::ifstream voter("voter.txt");
if(voter) { // check that the file is in a good (and open) state
std::string name;
while(std::getline(voter, name)) { // see notes
if(mainvoter == name) { // only return if you find a match
return true; // use true instead of 1
}
}
}
// return false here, when the whole file has been parsed (or you failed to open it)
return false; // and use false instead of 0
}
其他说明:
在检查文件中是否存在投票人的名称之前,请先将该文件的名称放入文件中.您需要检查名称是否首先存在,并且只有在文件中不存在该名称的情况下,才应将其添加到文件中.
You put the voter's name in the file before you check if the name exists in the file. You need to check if the name exists first and only if it does not exist in the file should you add it to the file.
您使用getline
读取了选民的姓名. getline
允许使用空格字符,而用于从文件读取的格式化输入voter >> name
则不允许(默认).因此,如果您输入"Nastya Osipchuk",您将无法找到匹配项,因为voter >> name
在第一个迭代中将读取"Nastya",而在下一个迭代中将读取"Osipchuk".
You used getline
to read the name of the voter. getline
allows for whitespace characters while the formatted input, voter >> name
, that you used to read from the file does not (per default). So, if you enter "Nastya Osipchuk", you would not be able to find a match since voter >> name
would read "Nastya" in the first iteration and "Osipchuk" in the next.
如果将searchname
函数移到main
上方,则可以避免前向声明.
You can avoid the forward declaration if you move the searchname
function above main
.