使用cin为char数组 [英] Using cin for char array

查看:1086
本文介绍了使用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;
}

键入:

12345
6789

12345 6789

它给了我:

6789

为什么我无法保存5个字的char数组'inp',它没有显示什么?第二个输入看起来正常。然而,当我出[3]或出[5],它似乎工作好吗?看来,两个字符数组[5],然后是[4]会导致问题...

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个字符和null终止符。当 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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆