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 数组
				
        
 
            
        基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				