C++ 使用 cin 将单个字母输入到字符中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24146242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using cin to input a single letter into a char
提问by starkiller
I have been trying to use "cin" to input a single letter to a char named letter. I have to input the letter using this method, but every time that I outputted the letter after the "cin" line I have a unrecognizable character.
我一直在尝试使用“cin”将单个字母输入到名为 letter 的字符中。我必须使用这种方法输入字母,但是每次在“cin”行之后输出字母时,我都会有一个无法识别的字符。
int main()
{
char letter[2];
cout << "Enter a letter: ";
cin >> letter;
cout << letter[2];
return 0;
}
Output:
输出:
Enter a letter: a
?
I also get random character output sometimes, such as "1" and "s".
有时我也会得到随机字符输出,例如“1”和“s”。
Any help would be greatly appreciated!
任何帮助将不胜感激!
Thanks!
谢谢!
回答by wolfPack88
You are not inputting or outputting the characters correctly. char letter[2]
is an array of 2 characters, not a single character. You want char letter
. Further, you are outputting letter[2]
, which is the third element of an array that only has two values (indexing in C++ starts from 0; the first element is letter[0]
and the second is letter[1]
)! The output will always be garbage. The correct code should be:
您没有正确输入或输出字符。char letter[2]
是一个包含 2 个字符的数组,而不是单个字符。你要char letter
。此外,您正在输出letter[2]
,它是只有两个值的数组的第三个元素(C++ 中的索引从 0 开始;第一个元素是letter[0]
,第二个元素是letter[1]
)!输出总是垃圾。正确的代码应该是:
char letter;
cout << "Enter a letter: ";
cin >> letter;
cout << letter;
return 0;
回答by F128247 Muhammad Awais
You just set the length of letters in array, and simply show that.
您只需在数组中设置字母的长度,然后简单地显示出来。
int main()
{
char single[1];
cout << "Enter any single letter\n";
cin >> single;
cout << "Your letter is\n";
cout << single;
return 0;
}