简体   繁体   English

Windows和Mac OS中的C ++字符串比较

[英]C++ string compare in Windows and Mac OS

When I run this code on Windows machine, it prints the buffer. 当我在Windows计算机上运行此代码时,它将打印缓冲区。 But when it comes to Mac OS, it doesn't print the buffer from the getline. 但是,对于Mac OS,它不会从getline中打印缓冲区。 I don't know why that is happen. 我不知道为什么会这样。 The Mac OS uses gcc 4.2.1, Windows uses MinGw 4.8.1. Mac OS使用gcc 4.2.1,Windows使用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上创建了文件,然后将其移至Mac OS,它将具有Windows行尾。

Windows is slightly odd - in a Windows-created text file, lines end in "\\r\\n". Windows有点奇怪-在Windows创建的文本文件中,行以“ \\ r \\ n”结尾。 This is usually translated back to "\\n" for you when you read the file. 当您阅读文件时,通常会将其翻译回“ \\ n”。 Mac OS does not do this translation back, so the buffer will actually contain "[Modal]\\r". Mac OS不会执行此转换,因此缓冲区实际上将包含“ [Modal] \\ r”。

dos2unix is a command line program that can do the translation for you, if that's what you want to do. dos2unix是一个命令行程序,如果您要这样做,它可以为您进行翻译。

I think the problem is that the file is not found in Mac OS. 我认为问题是在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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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