Determining the Newline character for the environment a C++ program is being compiled on

无人久伴 提交于 2020-01-14 07:38:07

问题


How does one determine the environment newline1 in C++? Google yields many results for C# and .NET but I didn't see any way to do it for non-CLI C++.

Additional info: I need to scan a const char* for the character(s).

1By "environment newline" I mean \r\n on Windows, \n on Linux, and \r on Mac.


回答1:


std::endl inserts a newline appropriate for the system. You can use a ostringstream to determine the newline sequence as a string at runtime.

#include <sstream>

int main()
{
    std::ostringstream oss;
    oss << std::endl;
    std::string thisIsEnvironmentNewline = oss.str();
}

EDIT: * See comments below on why this probably won't work.


If you know that your platforms will be limited to Windows, Mac, and Unix, then you can use predefined compiler macros (listed here) to determine the endline sequence at compile-time:

#ifdef _WIN32
    #define NEWLINE "\r\n"
#elif defined macintosh // OS 9
    #define NEWLINE "\r"
#else
    #define NEWLINE "\n" // Mac OS X uses \n
#endif

Most non-Windows and non-Apple platforms are some kind of Unix variant that uses \n, so the above macros should work on many platforms. Alas, I don't know of any portable way to determine the endline sequence at compile time for all possible platforms.




回答2:


For formatted text IO in C++ (and C), the new line character is always '\n'. If you want to know the binary representation of a new line for a given platform and file mode, open a file in the desired mode (e.g., text or binary, UTF-8, UTF-16, MCBS, etc.), write out '\n', close it, reopen it in binary, read in the entire file, and figure out what the actual binary encoding of '\n'. You may also have to account for the end-of-file character as well.




回答3:


Generally with a #define. But, for simple applications, opening a file in "text mode" will give you what you need.



来源:https://stackoverflow.com/questions/6864759/determining-the-newline-character-for-the-environment-a-c-program-is-being-com

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