简体   繁体   中英

C++ string compare in Windows and Mac OS

When I run this code on Windows machine, it prints the buffer. But when it comes to Mac OS, it doesn't print the buffer from the getline. I don't know why that is happen. The Mac OS uses gcc 4.2.1, Windows uses MinGw 4.8.1.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
const char *filename = "inputfile.txt";
string buffer;
ifstream infile(filename);

while(infile.good())
{
    getline(infile,buffer);
    if(buffer == "[Modal]")
        cout << "[Modal] Found!" << endl;
}

return 0;
}

If you created the file on Windows, and then moved it to Mac OS, it will have Windows line endings.

Windows is slightly odd - in a Windows-created text file, lines end in "\\r\\n". This is usually translated back to "\\n" for you when you read the file. Mac OS does not do this translation back, so the buffer will actually contain "[Modal]\\r".

dos2unix is a command line program that can do the translation for you, if that's what you want to do.

I think the problem is that the file is not found in Mac OS.

Change these statements

while(infile.good())
{
    getline(infile,buffer);
    if(buffer == "[Modal]")
        cout << buffer << endl;
}

to

if ( infile )
{
    while( getline(infile,buffer) )
    {
        if(buffer == "[Modal]")
        cout << buffer << endl;
    }
}
else
{
    cout << "File open error" << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM