函数getline()返回在Eclipse中,但空行中开发的C正常工作++

StackOverflow https://stackoverflow.com/questions/2543057

  •  23-09-2019
  •  | 
  •  

下面是我的代码:

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

我试过很多东西,但我无法找到问题。

有帮助吗?

解决方案

由于您使用的窗口尝试:

} 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);
}

其他提示

它将如果没有行包含正好0创建无限循环。例如0\n是不一样的东西0。我的猜测是,这是你的问题。

编辑:为了详细描述,函数getline应当丢弃换行符。或许文件错编码(即Windows与UNIX)的换行符。

您的主要问题是工作目录。点击 因为你正在使用它搜索从当前工作目录中的文件的相对路径指定的文件。工作目录可以通过你的开发环境中指定。 (注:工作目录是不一定相同目录下可执行的生活(这是初学者中常见的假设,但只有在非常特殊的情况下,持有))

虽然你有输入标记的特殊端“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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top