Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

Strange getline behavior in c++

I have the following file:

BB
7.501106 5.324115
7.997006 8.287983
11.314904 11.768281
...

And i am 100% sure that the file is ok, i have even shown newlines in vim with :set list :

BB$
7.501106 5.324115$
7.997006 8.287983$
11.314904 11.768281$
...

But when i open and read in the first line something wierd happens. I have the following code:

std::ifstream file(filename);
std::string line;
if (!file.is_open()) {
    std::cerr << "parseConfig: Error opening config file: " << filename << std::endl;
    exit(1);
}

getline(file, line);
std::cout << "line is: <" << line << ">" << std::endl;
if (line.compare("BB")) {
    std::cerr << "parseConfig: Error in config file, first line is not BB" << std::endl;
    exit(1);
}

Now i know the file is being opened correctly because we get all the way to the final error.

The print out is as following:

>ine is: <BB    //What!!!??  Why did this happen?
parseConfig: Error in config file, first line is not BB

Which strikes me as odd, its as if there is a carriage return in the text file. But i am so sure that there is not.

Any ideas?

Upvotes: 0

Views: 134

Answers (1)

John Kugelman
John Kugelman

Reputation: 361565

It looks like the file is in DOS mode. Check if vim displays [dos] at the bottom, or check file yourfile.txt.

Another way to check is by piping the file or the output of your program through cat -A (or cat -v if your cat doesn't have -A). Carriage returns will show up as ^M.

To convert to UNIX format, do :set ff=unix in vim and then save the file. Or use the dos2unix command-line tool if you have it.

Upvotes: 3

Related Questions