c++ - 使用cin.get读取字符数组

标签 c++ input char c-strings

我尝试编写一个程序,最多获取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/

相关文章:

c++ - 从文件输入文本到 char 变量

c++ - 声明一个(未使用的)整数导致整个程序出现故障?

c++ - 免费查询内存

c++ - 鼠标单击一次注册两次 C++/GLUT

python - 如何使用 Selenium 按住按键

c++ - 如何使用 cin.get() 来检测空的用户输入?

c# - 更正字符串中的字符?

c++ - 什么时候浮点变量不等于自身

angular - angular4 应用程序中输入的最小值和最大值

c - c 中要加倍的数字字符串