Using cin for char array

跟風遠走 提交于 2020-01-06 15:11:06

问题


Here is my code:

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

when I type:

12345 6789

It gives me:

6789

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...


回答1:


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


来源:https://stackoverflow.com/questions/29477567/using-cin-for-char-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!