这是我的代码:
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main() {
string line;
ifstream inputFile;
inputFile.open("input.txt");
do {
getline(inputFile, line);
cout << line << endl;
} while (line != "0");
return 0;
}
input.txt内容:
5 9 2 9 3
8 2 8 2 1
0
在Enclipse中,它会进入无限循环。我正在使用MinGW 5.1.6 + Eclipse CDT。
我尝试了很多东西,但我找不到问题。
答案 0 :(得分:2)
如果没有一行完全包含0
,它将创建一个无限循环。例如,0\n
与0
不同。我猜这是你的问题。
编辑:详细说明,getline应该丢弃换行符。也许您的文件的换行编码错误(即Windows与unix)。
答案 1 :(得分:2)
因为你在Windows上试试:
} while (line != "0\r");
最后一行存储为"0\r\n"
。 \n
被getline用作行分隔符,因此实际读取的行将为"0\r"
或
您可以使用命令
将dos格式文件转换为UNIX格式dos2unix input.txt
现在您的原始程序应该可行。该命令会将该行末尾的\r\n
更改为\n
在尝试打开文件后,您应该始终进行错误检查,例如:
inputFile.open("input.txt");
if(! inputFile.is_open()) {
cerr<< "Error opening file";
exit(1);
}
答案 2 :(得分:1)
您的主要问题是工作目录 因为您使用相对路径指定文件,所以它会从当前工作目录中搜索该文件。工作目录可以由dev环境指定。 (注意:工作目录不一定是可执行文件所在的目录(这是初学者中常见的假设,但仅在非常特殊的情况下才有效))。
虽然你有一个输入标记“0”的特殊结尾,你还应该检查getline()是否没有失败(因为它可能因其他原因(包括beady格式化输入)而出错。因此通常最好是在阅读时检查文件的状况。
int main()
{
string line;
ifstream inputFile;
inputFile.open("input.txt");
while((getline(inputfile, line)) && (line != "0"))
{
// loop only entered if getline() worked and line !="0"
// In the original an infinite loop is entered when bad input results in EOF being hit.
cout << line << endl;
}
if (inputfile)
{
cout << line << endl; // If you really really really want to print the "0"
// Personally I think doing anything with the termination
// sequence is a mistake but added here to satisfy comments.
}
return 0;
}