c++ getline reads entire file in Windows

微笑、不失礼 提交于 2019-12-04 05:43:28

问题


This looks like a similar question to this one, however I think my case might actually be a bit different. The code is as below:

void readOmronResults(string fileName)
{
    ifstream inFile(fileName);
    ofstream testRead("test_read.txt");

    string line;
    //getline(inFile, line);
    //cout << line << endl;
    while (getline(inFile, line))
    {
        testRead << line << endl;
    }


    inFile.close();
    testRead.close();

    cout << "Finished reading omron results" << endl;
}

testRead is just used for debugging. The input file is a .csv file which looks like:

    IMAGE,RIGHT_EYE_IN_X,RIGHT_EYE_IN_Y,RIGHT_EYE_OUT_X,RIGHT_EYE_OUT_Y,LEFT_EYE_IN_X,LEFT_EYE_IN_Y,LEFT_EYE_OUT_X,LEFT_EYE_OUT_Y
    0001_2m_-15P_-10V_-10H,2386,1627,2171,1613,2754,1623,3009,1583
    0001_2m_-15P_-10V_-15H,2377,1620,2171,1606,2750,1611,3003,1574
    0001_2m_-15P_-10V_-5H,2376,1614,2166,1599,2752,1609,3012,1577
           ...

If I run the above code, the output in test_read.txt is exactly the same as it is in the input file. However if I restore the two commented out lines, the console window shows all the lines in the input file( repeatedly from the second line) and the test_read.txt is empty. From the linked post I guess it probably has something to do with the difference of line endings in different operating systems. My operating system is Windows and according to my text editor the original input file is Mac-OS style. But if it is because of this, why is the original code (with the two lines commented out) able to give a correct result?

My IDE is Visual Studio 2012 and my machine is 64-bit.


回答1:


My operating system is Windows and according to my text editor the original input file is Mac-OS style.

Yes, this is the problem. Windows' C and C++ standard libraries will assume that text files use the Windows line ending, U+0D U+0A.

"Mac OS style" is an odd thing for the text editor to say, because the other line ending in common use U+0A which is common to the entire Unix family including Linux. Long ago, Mac OS used U+0D which makes the phrase "Mac OS style" ambiguous and anachronistic.

But if it is because of this, why is the original code (with the two lines commented out) able to give a correct result?

It didn't. Both versions of the program treat the file as if it contains one very long line.




回答2:


If they are Mac OS endings '\r', according to the docs: http://www.cplusplus.com/reference/string/string/getline/ this behaviour is not surprising.

Paraphrasing the docs: when not giving a delimiter, getline will ready until a newline ('\n') character is encountered.



来源:https://stackoverflow.com/questions/30010300/c-getline-reads-entire-file-in-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!