开发者

What is the difference between '\n' or "\n" in C++?

I've seen the new line \n used 2 different ways in a few code examples I've been looking at. The first on开发者_开发知识库e being '\n' and the second being "\n". What is the difference and why would you use the '\n'?

I understand the '\n' represents a char and "\n" represents a string but does this matter?


'\n'is a character constant.

"\n" is a pointer to character array equivalent to {'\n', '\0'} (\n plus the null terminator)

EDIT

I realize i explained the difference, but didn't answer the question.

Which one you use depends on the context. You use '\n' if you are calling a function that expects a character, and "\n", if it expects a string.


'\n' is a char literal. "\n" is a string literal (an array of chars, basically).

The difference doesn't matter if you're writing it to an ordinary stream. std::cout << "\n"; has the same effect as std::cout << '\n';.

In almost every other context, the difference matters. A char is not in general interchangeable with an array of chars or with a string.

So for example std::string has a constructor which takes a const char*, but it doesn't have a constructor which takes a char. You can write std::string("\n");, but std::string('\n'); doesn't compile.

std::string also has a constructor which takes a char and the number of times to duplicate it. It doesn't have one that takes a const char* and the number of times to duplicate it. So you can write std::string(5,'\n') and get a string consisting of 5 newline characters in a row. You can't write std::string(5, "\n");.

Any function or operation that you use will tell you whether it's defined for a char, for a C-style string, for both via overloading, or for neither.


'\n' is a char constant.

"\n" is a const char[2].

So usage is something like this:

char newLine = '\n';
const char* charPointerStringNewLine = "\n"; // implicit conversion
const char charStringNewLine[2] = "\n";

string stringNewLine( "\n" );

So in short: one is a pointer to a character array, the other is a single character.


Single quotes denote a character and double quotes denote a string. Depending on the context, you can choose which data type to work with.


I understand the '\n' represents a char and "/n" represents a string but does this matter?

If you understand this, then it should be clear that it does indeed matter. Overloaded functions in the C++ standard library often hide this fact, so maybe an example from C will be more useful: putchar takes a single character, so only '\n' is correct, whereas puts and printf take a string, and in that case, only "\n" is correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜