문제

Here is my code:

#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 content:

5 9 2 9 3
8 2 8 2 1
0

In Enclipse, it goes to infinite-loop. I'm using MinGW 5.1.6 + Eclipse CDT.

I tried many things but I couldn't find the problem.

도움이 되었습니까?

해결책

Since you are on windows try:

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

The last line is stored as "0\r\n". The \n is used as the line delimiter by getline so the actual line read will be "0\r"

or

you can convert the dos format file to UNIX format using command

dos2unix input.txt

Now your original program should work. The command will change the \r\n at the end of the line to \n

Also you should always do error checking after you try to open a file, something like:

inputFile.open("input.txt");
if(! inputFile.is_open()) {
 cerr<< "Error opening file";
 exit(1);
}

다른 팁

It will create an infinite loop if no line contains exactly 0. For example 0\n is not the same thing as 0. My guess is that that is your problem.

EDIT: To elaborate, getline should be discarding the newline. Perhaps the newline encoding of your file wrong (i.e. windows vs. unix).

운 좋게도 일부는 나를 위해 블로그에서 그것을했습니다. https://electrovoid.wordpress.com/2012/05/03 / pps-hide-show-to»

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top