简体   繁体   中英

C++ User input string error

I am getting a strange error when I am trying to get user input as a string.

I have the correct includes;

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

This is the code, where when executed I get the error;

write("Enter your name");
string name = readString();
write(name);

The above code calls these two functions;

void game::write(std::string message)
{
    cout << message << "\n";
}

string game::readString()
{
    string userInput = NULL;
    std::cin >> userInput;
    return userInput;
}

This is the error I get: C ++错误

I have tried re-building the solution - should I used a char array rather than string as the data container for text in my application??

You can not initialize a string from a NULL pointer. Try:

string userInput = "";

or simply

string userInput;

See here and check ctor no. 5, based on the C++ standard:

21.4.2 basic_string constructors and assignment operators [string.cons]

basic_string(const charT* s, const Allocator& a = Allocator());

8 Requires: s shall not be a null pointer.

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