当文本文件位于行尾时如何检测"0"?

How to detect '0' when it comes at the end of the line for a text file?

本文关键字:检测 何检测 文件 文本 于行尾      更新时间:2023-10-16

我正在扫描一个文本文档,它的格式是这样的:

3 10

1阿拉伯数字
阿拉伯数字

1
3
1
1
1阿拉伯数字
阿拉伯数字
顶部的前两个整数分别表示候选人的数量和票数。我很难检测到票数的字符串"10"

由于我正在使用 c++,到目前为止我已经尝试这样做:

string line;
int candidateTally;
int voteTally;
ifstream file("votes.txt");
//detect the candidate tally "3"
getline(file, line);
candidateTally = atoi(line.c_str());
cout << candidateTally << endl;
//output the candidate tally "10" but it's only outputting "1"
getline(file, line);
cout << line;

我不太确定如何拿起 0 的第二个字符以获得完整的"10"字符串似乎 getline 函数在拾取 0 之前切断,因为这可能代表""字符?我想让它检测"0"并将其包含在带有"1"的字符串中,以便我可以将其转换为它应该是 10 的 int。

我该如何解决这个问题?

问问自己getline是做什么的...是的,它一条线

所以第一个调用"获取"整行"3 10",第二个调用"获取文件中的下一行:"1"

应使用 >> 运算符从文件中读取传入值。这也将消除弄乱atoi()和字符指针的需要。

请改用以下内容:

int candidateTally;
int voteTally;
ifstream file("votes.txt");
//detect the candidate tally "3", and the vote tally "10".
file >> candidateTally >> voteTally;
cout << candidateTally << endl;
cout << voteTally << endl;

operator>>忽略空格。它的第一个调用(file >> candidateTally)将"吃掉"3",第二次调用(>> votetally)将跳过空格,然后拾取"10"。精度可以在这里阅读,但细节很难阅读。

如果您要获得候选人和选票数的行,则没有理由使用atoi

std::string line;
int candidateTally;
int voteTally;
std::ifstream file("votes.txt");
if (std::getline(file, line))
{
    std::istringstream iss(line);
    iss >> candidateTally >> voteTally; // you should also add error handling here
    // ...
}
else
{
    // handle the error here
}