开发者

Question about char input

This is what I'm trying to do...

char input[4];
cin &开发者_StackOverflow中文版gt;> 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 "P F" 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]

Why do I get that weird character instead of 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 >>.

Thus after that cin >> input line, your input will look like

   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(input, 4);
cout << ...;

(Or better, use std::string which has flexible string length.)


Extracting from cin will break on a space, so it's only reading the P. If you want to read a line from the user you should look at 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; however, since it doesn't know how many characters your input array can hold, it can possibly overrun 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 "P F" actually only reads "P". So, your input variable gets filled with "P" (which is NUL-terminated, so you actually have 'P' then '\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::string result;
std::getline(std::cin,result);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜