cin是否会将\ n从键盘输入的\ n识别为换行符? [英] Will cin recognize \n typed in from keyboard as a newline character?

查看:585
本文介绍了cin是否会将\ n从键盘输入的\ n识别为换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的初学者,所以很抱歉如果这个问题听起来很愚蠢.

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

我制作了这个小程序来帮助我熟悉cin的属性:

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

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string next;
    cout<<"Enter your input.\n";
    cin>>next;
    cout<<next;
    return 0;
}

从键盘输入中键入\n时,返回了\n.

When I typed in \n from the keyboard input, I was returned \n.

此外,当我将变量 next 从字符串更改为字符并提供与上述相同的输入时,我只返回了\.

Also, when I changed the variable next from a string to a character and gave it the same input as above, I was returned only a \.

我的问题是:为什么我不返回新行? cin不能将键盘上的\n输入识别为换行符吗?还是只适用于cout?

My question is: Why am I not returned with a new line instead? Doesn't cin recognize \n type in from keyboard as a newline character? Or is it just applicable to cout?

推荐答案

\n是C ++中的转义序列.当它出现在字符常量或字符串文字中时,两个字符序列将替换为表示默认基本编码中的新行的单个字符(在现代系统中几乎始终为0x0A). C ++定义了许多这样的转义序列,都以\开头.

\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 \.

输入的映射方式不同,在许多情况下,取决于设备.从键盘上读取时,大多数系统将缓冲一行,并且仅在按下Enter键时才从该行返回字符;他的Enter键发送给C ++程序的内容可能会有所不同,并且无论是在文本模式下打开文件还是在二进制模式下打开文件也会有所不同,在C ++库中,C ++库应与操作系统协商以确保Enter键总是导致由\n表示的单个字符. (std::cin始终在文本模式下打开.)键盘驱动程序是否对\做特殊操作取决于该驱动程序,但大多数情况不会.从键盘输入时,C ++从未对\做任何特别的操作(并且\n在C ++源代码中没有字符串文字和字符常量的特殊含义).

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).

这篇关于cin是否会将\ n从键盘输入的\ n识别为换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆