1

这是我的代码:

#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。

我尝试了很多东西,但我找不到问题所在。

4

3 回答 3

2

由于您在 Windows 上,请尝试:

} while (line != "0\r");

最后一行存储为"0\r\n". 被\ngetline 用作行分隔符,因此实际读取的行将是"0\r"

或者

您可以使用命令将 dos 格式文件转换为 UNIX 格式

dos2unix input.txt

现在您的原始程序应该可以工作了。该命令将\r\n在行尾更改为\n

此外,在尝试打开文件后,您应该始终进行错误检查,例如:

inputFile.open("input.txt");
if(! inputFile.is_open()) {
 cerr<< "Error opening file";
 exit(1);
}
于 2010-03-30T05:55:42.640 回答
2

如果没有行正好包含0. 例如0\n0. 我的猜测是那是你的问题。

编辑:详细说明, getline 应该丢弃换行符。也许您的文件的换行编码错误(即 windows 与 unix)。

于 2010-03-30T05:39:00.883 回答
1

您的主要问题是工作目录。
因为您使用相对路径指定文件,所以它会从当前工作目录中搜索文件。工作目录可以由您的开发环境指定。(注意:工作目录不一定与可执行文件所在的目录相同(这是初学者的普遍假设,但仅在非常特殊的情况下才成立))。

尽管您有一个特殊的输入标记“0”结尾,但您还应该检查 getline() 是否失败(因为它可能由于其他原因(包括格式化输入)而出错。因此,通常最好检查条件当你阅读它的文件。

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;
}
于 2010-03-30T06:47:15.887 回答