#define SIZE 30
// some code
ifstream outFile;
outFile.open("lab.txt"); // opening lab document which has a sentence
char buffer[SIZE]; // buffer for storing the sentence when reading from file
while (!outFile.eof()) // reads lab.txt until eof
{
// two methods for output to screen which print sentence on debugging
// but program doesn't terminate
outFile >> buffer;
cout << buffer << endl;
// outFile.getline(buffer, SIZE);
// cout << buffer << endl;
}
此代码用于从序列文件中读取,例如lab.txt
。问题是,当我在文件中运行句子时,我会被打印,但后面是一个无限循环,它会保留打印空间,因此程序永远不会终止。我已经尝试了两种方法,但结果都是一样的。
欢迎任何帮助?
答案 0 :(得分:1)
从文件中读取的正确方法如下:
while(outFile >> buffer) {
cout << buffer << endl;
}
使用outFile.eof()
作为条件是有问题的。
答案 1 :(得分:1)
只需使用
while(outFile.getline(buffer, SIZE))
{
.....
}
而不是outFile.eof()