Using cin for char array(将 cin 用于 char 数组)
问题描述
这是我的代码:
#include <iostream>
using namespace std;
int main(){
char inp[5], out[4];
cin >> inp >> out;
cout << inp << endl;
cout << out << endl;
system("pause");
return 0;
}
当我输入时:
123456789
它给了我:
6789
为什么我没有保存 5 个字的 char 数组 'inp' 却什么也没显示?第二个输入看起来很正常.但是,当我设置 out[3] 或 out[5] 时,它似乎可以正常工作?似乎 [5] 后跟 [4] 的两个 char 数组会导致问题...
Why I failed to save the 5 words char array 'inp' and it showed nothing? The second input looks normal though. However, when I set out[3] or out[5], it seems to work alright? It seem that two char array of [5] then followed by [4] would cause problem...
推荐答案
我看到你输入(类型)1234567890个字符为inp[5]输入数据-这是一个问题,因为 imp 数组能够存储 4 个字符和空终止符.当 cin >>inp 将超过 4 个字符存储到 inp 数组中,这会导致数据出现问题(类似于未定义的行为).因此解决方案可以为数据分配更多内存,例如:
I see that you enter (type) 1234567890 characters to input data for inp[5] - it is a problem because imp array is able to store 4 characters and null-terminator. When cin >> inp store more than 4 characters to inp array it leads to problem with data (somthing like undefined behaviour). So solution can be in allocation more memory for data, e.g.:
#include <iostream>
using namespace std;
int main(){
char inp[15], out[15]; // more memory
cin >> inp >> out;
cout << inp << endl;
cout << out << endl;
system("pause");
return 0;
}
这篇关于将 cin 用于 char 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 cin 用于 char 数组
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
