[英]Question about char input
This is what I'm trying to do... 这就是我想要做的...
char input[4];
cin >> input;
cout << "Input[0]: " << input[0] << "Input[1]: " << input[1] << "Input[2]: " << input[2] << "Input[3] " << input[3]<< "Input[4] " << input[4] <<endl;
However, when I enter "PF" I get an output of this: Input[0]:P Input[1]: Input[2]:(A weird looking square with two zeros on top and a zero and 4 on the bottom) Input[3] Input[4] 但是,当我输入“ PF”时,我得到以下输出:Input [0]:P Input [1]:Input [2] :(看起来很奇怪的正方形,顶部有两个零,底部有一个零和4)输入[3]输入[4]
Why do I get that weird character instead of F? 为什么我得到那个奇怪的字符而不是F?
cin >>
separates inputs by a space, hence when you enter P<space>F
, only the P
is accepted into input
, and F
is queued for the next cin >>
. cin >>
用空格分隔输入,因此,当您输入P<space>F
,只有P
被接受为input
,并且F
排队等待下一个cin >>
。
Thus after that cin >> input
line, your input
will look like 因此,在cin >> input
行之后,您的input
将类似于
input[0] = 'P';
input[1] = '\0';
// input[2] = garbage;
// input[3] = garbage;
// input[4] = buffer-overflow;
Perhaps you want to use cin.getline
: 也许您想使用cin.getline
:
cin.getline(input, 4);
cout << ...;
(Or better, use std::string
which has flexible string length.) (或者更好,使用具有灵活字符串长度的std::string
。)
Extracting from cin
will break on a space, so it's only reading the P
. 从cin
提取将在一个空格上中断,因此仅读取P
If you want to read a line from the user you should look at getline()
如果要从用户读取一行,则应查看getline()
std::string input;
std::getline(std::cin, input);
What you are doing is actually incredibly dangerous. 实际上,您正在做的事情非常危险。 Your input
variable is actually degrading into an object of type char*
, so it is actually attempting to read a string into your input
variable; 您的input
变量实际上正在降级为char*
类型的对象,因此实际上是在尝试将字符串读取到您的input
变量中; however, since it doesn't know how many characters your input
array can hold, it can possibly overrun input
. 但是,由于它不知道您的input
数组可以容纳多少个字符,因此它可能会覆盖input
。 Therefore, the code as you have it is actually a buffer overflow vulnerability . 因此,您拥有的代码实际上是一个缓冲区溢出漏洞 。 Instead, you should use: 相反,您应该使用:
for (int i = 0; i < 4; i++ ){ std::cin >> input[i]; }
As to why you get that weird character... the stream extraction operator >> reads words that are separated by spaces, so "PF" actually only reads "P". 至于为什么得到这个奇怪的字符……流提取运算符>>读取用空格分隔的单词,因此“ PF”实际上只读取“ P”。 So, your input variable gets filled with "P" (which is NUL-terminated, so you actually have 'P' then '\\0'). 因此,您的输入变量将填充“ P”(它是NUL终止的,因此实际上是“ P”然后是“ \\ 0”)。 The remaining elements are uninitialized and so have whatever garbage that happens to be there. 其余元素未初始化,因此碰巧存在任何垃圾。 Also, I should add that if you did want to read string, then std::getline is a very good way to read std::string objects from the input as in: 另外,我应该补充一点,如果您确实想读取字符串,那么std :: getline是从输入中读取std :: string对象的一种很好的方式,如下所示:
std::string result; std::getline(std::cin,result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.