cpp getline 在 while 循环中工作一次,然后读取直到文件末尾
Cpp getline in a while loop works once, then reads until the end of the file
我正在编写一个将命令重定向文件作为标准输入的程序,因此我 运行 我的程序使用 ./teamBalancer < inputFile.txt > outputFile.txt
而不是 cin
从键盘获取输入。
我遇到的问题是 while
循环中的 getline
完美地读取了第一行并输出正常,但它只是在一行中读取文件的其余部分。我尝试了从 stringstream
到 getline
的所有方法,并阅读了很多论坛。为什么会这样?
这是我的代码:
//USER INPUT--------------------------------------------------------------
while (cin) {
string attackString, defenseString;
getline(cin, attackString, ',');
getline(cin, defenseString);
int attack, defense;
attack = atoi(attackString.c_str());
defense = atoi(defenseString.c_str());
cout<<attack<<" "<<defense<<endl;
}
样本输入是这样的:
5,1
9,1
7,4
1,3
1,3
10,4
4,5
7,4
对应的输出是...
5 1
9 1
0 0
这两个都是txt文件,最后输出0 0是因为最后一行是空的?我不明白为什么 getline
不能像第一个那样继续逐行读取文件。
非常感谢任何提供帮助的人,如果您需要任何说明,请告诉我!谢谢:)
您提供的代码看起来不错。我在 Windows 下测试它,没有任何更改,得到以下结果:
5 1
9 1
7 4
1 3
1 3
10 4
4 5
7 4
0 0
看来您的输入文件编码有问题。
你能检查一下你输入的 txt 的行尾吗?它们都一样吗?EOL 字符是您系统的默认字符吗?
最后一行的 0 0 是 cin 的末尾仍然包含一些东西(EOF 字符),但它无法将其转换为所需的数字,为避免这种情况,您可以使用:
while (!cin.eof())
现在您正在检查您是否在文件末尾。
对不起,目前我不能写评论。
br,
津乔纳斯
我正在编写一个将命令重定向文件作为标准输入的程序,因此我 运行 我的程序使用 ./teamBalancer < inputFile.txt > outputFile.txt
而不是 cin
从键盘获取输入。
我遇到的问题是 while
循环中的 getline
完美地读取了第一行并输出正常,但它只是在一行中读取文件的其余部分。我尝试了从 stringstream
到 getline
的所有方法,并阅读了很多论坛。为什么会这样?
这是我的代码:
//USER INPUT--------------------------------------------------------------
while (cin) {
string attackString, defenseString;
getline(cin, attackString, ',');
getline(cin, defenseString);
int attack, defense;
attack = atoi(attackString.c_str());
defense = atoi(defenseString.c_str());
cout<<attack<<" "<<defense<<endl;
}
样本输入是这样的:
5,1
9,1
7,4
1,3
1,3
10,4
4,5
7,4
对应的输出是...
5 1
9 1
0 0
这两个都是txt文件,最后输出0 0是因为最后一行是空的?我不明白为什么 getline
不能像第一个那样继续逐行读取文件。
非常感谢任何提供帮助的人,如果您需要任何说明,请告诉我!谢谢:)
您提供的代码看起来不错。我在 Windows 下测试它,没有任何更改,得到以下结果:
5 1
9 1
7 4
1 3
1 3
10 4
4 5
7 4
0 0
看来您的输入文件编码有问题。 你能检查一下你输入的 txt 的行尾吗?它们都一样吗?EOL 字符是您系统的默认字符吗?
最后一行的 0 0 是 cin 的末尾仍然包含一些东西(EOF 字符),但它无法将其转换为所需的数字,为避免这种情况,您可以使用:
while (!cin.eof())
现在您正在检查您是否在文件末尾。
对不起,目前我不能写评论。
br,
津乔纳斯