我已经尝试过了,但我没有运气,我希望让用户输入 5 个字母,然后将它们打印出来。
string input = "";
const int max = 5;
char string[max] = { };
cout << "Please enter 5 letters: " << endl;
cin.getline(string, max, '\n');
cout << "Your letters :" << string[max];
我已经尝试过了,但我没有运气,我希望让用户输入 5 个字母,然后将它们打印出来。
string input = "";
const int max = 5;
char string[max] = { };
cout << "Please enter 5 letters: " << endl;
cin.getline(string, max, '\n');
cout << "Your letters :" << string[max];
我想我知道什么不起作用:
首先,你string[max]
在最后打印出来。由于string
是 achar[]
的大小max
,它实际上在索引处没有数据——它的max
索引是0
to max-1
。您实际上是在string
变量字符之后立即从内存中的任何内容中打印出一个随机字符。
因此,而不是<< string[max]
在最后一行,它应该是<< string
.
其次,在进行更改后,它似乎仍然只打印 4 个字符,而不是输入的 5 个字符。这是因为char[]
s 形式的字符串有一个空终止符。因此,由于您告诉cin.getline
只填写 5 个字符string
,它会用输入中的实际字符填充前 4 个字符,然后最后一个字符是'\0'
.
因此,如果输入为"hello"
,string
则将包含以下值:{ 'h', 'e', 'l', 'l', '\0' }
. 然后当你打印它时,数组中当然只有 4 个字符。
还有两个注意事项:string input
在您的程序中的任何地方都没有使用,所以它应该被排除在问题之外。而且,你真的应该把你的char string[max]
变量叫做别的东西,以减少混淆。
我希望这有帮助!