c++ - 使用 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;
}
解决方案
while 语句中的条件无效。有一个错字
while (index < MAX -1 &&
(str[index++]==cin.get()) != '\n');
^^^
写
while (index < MAX -1 &&
(str[index++] = cin.get()) != '\n');
考虑到换行符'\n'
可以存储在结果字符串中。
推荐阅读
- jwt - Fusion Auth /api/jwt/issue api 未按预期工作
- input - 所需的指标是否总是必须是红色的并且在 Web 表单上的标签级别?
- python - 在 Tensorflow 中分析 RNN vs CNN vs NN 结果
- python - 如何在 Python 中按比例混合颜色?
- c# - 如何通过 ASP.NET MVC 控制器使用 jquery ajax 和结构化参数将 HTML 表数据一次性插入 SQL Server
- windows - 升级到 WSL 2 时出错:端点映射器没有更多可用的端点
- python - datetime 在某些情况下错误地更改日期和月份
- python - 如何将样条拟合转换为分段函数?
- javascript - 计算直到下个月的秒数
- javascript - 在铬中杀死角度