char* and cin in C++

前端 未结 2 823
梦如初夏
梦如初夏 2021-01-01 06:00

I would like to input a string of indefinite length to a char * variable using cin;

I can do this:

char * tmp = \"My string\";
cout << tmp <         


        
2条回答
  •  时光说笑
    2021-01-01 06:41

    Couple of issues:

    char * tmp
    cin >> tmp;
    

    tmp is not allocated (it is currently random).

    operator>> (when used with char* or string) reads a single (white space separated) word.

    Issue 1:

    If you use char* and allocate a buffer then you may not allocate enough space. The read may read more characters than is available in the buffer. A better idea is to use std::string (from this you can get a C-String).

    Issue 2:

    There is no way to read indefinite string. But you can read a line at a time using std::getline.

    std::string line;
    std::getline(std::cin, line);
    
    char* str = line.data();
    

提交回复
热议问题