Will cin recognize \n typed in from keyboard as a newline character?

前端 未结 3 1294
死守一世寂寞
死守一世寂寞 2021-01-21 05:08

I am a beginner for C++ so I\'m sorry if this question sounds stupid..

I made this little program to help me get familiar with the properties of cin:

<
相关标签:
3条回答
  • 2021-01-21 05:40

    Technically speaking, this depends on things outside your program, but assuming your terminal simply passes the individual bytes corresponding to the '\' and 'n' characters (which I think any sane one will), then the behavior you're seeing is expected.

    "\n" is nothing more than a shortcut added to the programming language and environment to let you more easily represent the notion of the ASCII return key. It's not a character itself, just a command to tell the program to generate a non-printable character that corresponds to pressing the Enter key.

    Let's say you're in Notepad or whatever and you press the Tab key. It tabs over a spot. Typing "\t" just enters the literal characters "\" and "t". Internally, whoever wrote Notepad had to say what it should do when the user pressed Tab, and he did so by using the mnemonic like

    if(key == '\t') {
        // tab over 
    }
    
    0 讨论(0)
  • 2021-01-21 05:58

    \n is an escape sequence in C++; when it appears in a character constant or a string literal, the two character sequence is replaced by the single character representing a new line in the default basic encoding (almost always 0x0A in modern systems). C++ defines a number of such escape sequences, all starting with a \.

    Input is mapped differently, and in many cases, depending on the device. When reading from the keyboard, most systems will buffer a full line, and only return characters from it when the Enter key has been pressed; what he Enter key sends to a C++ program may vary, and whether the file has been opened in text mode or binary mode can make a difference as well—in text mode, the C++ library should negotiate with the OS to ensure that the enter key always results in the single character represented by \n. (std::cin is always opened in text mode.) Whether the keyboard driver does something special with \ or not depends on the driver, but most don't. C++ never does anything special with \ when inputting from a keyboard (and \n has no special meaning in C++ source code outside of string literals and character constants).

    0 讨论(0)
  • 2021-01-21 05:58

    If you need your program to recognize \n as a new line character at input you can check this out: https://stackoverflow.com/a/2508814/815812

    What Michael say is perfectly correct.

    You can try out in similar way.

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