首页 > 解决方案 > 使用 cin.get 读取字符数组

问题描述

我尝试编写一个最多包含 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;
}

标签: c++inputcharc-strings

解决方案


while 语句中的条件无效。有一个错字

while (index < MAX -1 &&
        (str[index++]==cin.get()) != '\n');
                     ^^^

while (index < MAX -1 &&
        (str[index++] = cin.get()) != '\n');

考虑到换行符'\n'可以存储在结果字符串中。


推荐阅读