将 cin 用于 char 数组 [英] Using cin for char array

查看:26
本文介绍了将 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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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