我尝试编写一个程序,最多获取20个字符,并将它们索引为字符数组,然后打印出该数组。该程序可以编译,但是输出是随机单词和符号来代替变量。知道为什么吗?
# include <iostream>
using namespace std;
int main ()
{
const int MAX = 20;
char str[MAX];
int index = 0;
while (index < MAX -1 &&
(str[index++]==cin.get()) != '\n');
str[index]='\0';
cout<<"What i typed is _"<<str<<endl;
return 0;
}
最佳答案
while语句中的条件无效。有错字
while (index < MAX -1 &&
(str[index++]==cin.get()) != '\n');
^^^
写
while (index < MAX -1 &&
(str[index++] = cin.get()) != '\n');
考虑到可以将新行字符
'\n'
存储在结果字符串中。
关于c++ - 使用cin.get读取字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61965647/