char* and cin in C++

前端 未结 2 846
梦如初夏
梦如初夏 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:51

    Well, you havn't created an object for the char* to point to.

    char* tmp = new char[MAX_LENGTH];
    

    should make it work better (you have to define MAX_LENGTH). Another way to do this is:

    std::string strtmp;
    cin >> strtmp;
    const char* tmp = strtmp.c_str();
    

    This method would mean that you need not use new.

提交回复
热议问题