In these two cases I am entering \n
as user input (in a string) in one and I am making \n
as a part of string in the program itself (no user input):
string str1;
cin>>str1; //case 1 - \n entered as the part of the input
string str="hello\n"; //case 2
in case 1 \n
is considered as a part of the input string whereas in case 2 it is considered as newline - why?
Escape sequences are compiler-time only literals. When your compiler comes across a \ in a string, it looks for a pattern afterwards to determine the value. When you read in from the console, the input is read one character at a time. Most debuggers will show the inputted string as "hello\\n"
, or broken up into individual characters:
'h','e','l','l','o','\\','n'
When you manually set the string in the code, such as string str = "hello\n"
, the compiler recognizes the escape sequence and treats it as the single character '\n'. This allows programmers to have shorthand for printing characters without going and printing their ASCII values. Users, on the other hand, have an enter button to conveniently add a newline, and programs are generally oriented to have a human-readable interface(i.e., if I type a '\' character I expect it to be a '\' if I have no experience with computers)
Another note about cin is that it uses newline characters other whitespace to distinguish between kinds of input. The function getline is meant for string input for getting around this, but the stream extraction is done from whitespace to whitespace so it is consistent with all data types(int,float,char,etc)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments