Ninja
Ninja

Reputation: 48

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 ?

Upvotes: 1

Views: 152

Answers (1)

Brett Wolfington
Brett Wolfington

Reputation: 6627

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)

Upvotes: 5

Related Questions