将 cin 用于 char 数组

2022-01-12 00:00:00 arrays char c++ cin

这是我的代码:

#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;
    }

相关文章