Get platform specific end of line character in C++/Qt

后端 未结 4 1458
孤城傲影
孤城傲影 2021-01-18 17:27

Is there anything for getting right end-of-line symbol for any platform? I mean, I can use \\n for Windows and Unix if I want to write EOL to file, but there is

相关标签:
4条回答
  • 2021-01-18 17:45

    You can try using the std::endl

    0 讨论(0)
  • 2021-01-18 17:50

    I use this bit of code:

        const QChar newline(QChar('\n'));
        const QChar cr('\r');
        #ifdef __linux__ 
            const QChar eol = newline);
        #elif _WIN32
            const QString eol = QString(cr) + QString(newline);
        #else
            const QChar eol = cr;
        #endif
    

    I have not tested the else branch because I do very little work on systems that aren't either linux or windows (mac for example), so one would have to test that one's self.

    The linux, and windows branches work well for me for splitting strings into lines on windows and linux.

    0 讨论(0)
  • 2021-01-18 17:54

    Try

    QString::split(QRegularExpression{R"-((\r\n?|\n))-"})
    

    This uses a C++11 raw string literal to create a regex that matches all three possibilities:

    • CR only (Mac)
    • CR+LF (Win)
    • LF (Unix)

    If you can not use C++11, you will have to manually escape the regex:

    "(\\r\\n?|\\n)"
    

    That should do the trick.

    0 讨论(0)
  • 2021-01-18 17:56

    When you are writing a file in text mode, the "\n" character should be reinterpreted as whatever is appropriate for that system. For Windows, that means CRLF (carriage return, line feed), on Unix, it's just LF alone, and the Macintosh standard is a CR by itself.

    When you are reading, be ready to end a line at either one of those characters, but if you find a carriage return, check to see if there is a line feed immediately after it, and if there is, consider it part of the same line.

    0 讨论(0)
提交回复
热议问题