Using cin for char array

前端 未结 2 1253
無奈伤痛
無奈伤痛 2020-12-22 03:30

Here is my code:

#include 
using namespace std;

int main(){
    char inp[5], out[4];
    cin >>         


        
2条回答
  •  余生分开走
    2020-12-22 04:33

    When you read into a character array the stream keeps reading until it encounters whitespace, the stream is not aware of the size of the array that you pass in so happily writes past the end of the array so if your first string is longer than 4 characters your program will have undefined behaviour (an extra character is used after your input for the null terminator).

    Fortunately c++20 has fixed this issue and the stream operators no longer accept raw char pointers and only accept arrays and will only read up to size - 1 characters.

    Even with c++20 the better solution is to change your types to std::string which will accept any number of characters end even tell you how many characters it contains:

    #include 
    
    int main(){
        std::string inp, out;
        std::cin >> inp >> out;
        std::cout << inp << "\n";
        std::cout << out << "\n";
        return 0;
    }
    

提交回复
热议问题