简体   繁体   中英

When reading a C-style string in c++ an error appears

Firstly, look at the following simple code.

int main(){
    char *name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Your name is: " << name;

    return 0;
}

The previous code gives me the following error warning: deprecated conversion from string constant to 'char*' .
but I have been solved the problem by:

const char *name;

After compile the code, I have another error no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream<char>}' and 'const char*') .

What the reason of the previous error, and how to solve it ?

You haven't initialized any memory into which the string can be read. char * is a pointer to a location in memory where a string can be read, but the memory first has to be allocated using new or malloc .

However, in C++ there is another, better option: use std::string :

#include <string>

int main()
{
    std::string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Your name is: " << name;

    return 0;
}

If you are set on using a c-string, you could do allocate memory and do something like the following:

int main()
{
    char name[MAX_SIZE];
    cout << "Enter your name: ";
    cin.get(name, MAX_SIZE);
    cout << "Your name is: " << name;

    return 0;
}

(Thanks to Neil Kirk for the improvements)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM