1

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++ Error

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??

1 Answer 1

5

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.

4
  • 1
    That worked completely - I am such a N00b!! I feel a fool to have asked this on StackOverflow - now I see how simple the answer was. Mar 19, 2013 at 17:23
  • @ConnorJackson: Happens to everyone in the beginning. IIRC, there were even STLs that in the past would have accepted your code. Mar 19, 2013 at 17:29
  • @Danel Frey - I have 2 other read functions, readInt and readChar - on both of those they accept NULL - but looking at it string is different as its also like a class type rather than a data type. - if that makes sense. Mar 19, 2013 at 17:38
  • @ConnorJackson: Generally, I try to avoid NULL as much as possible. Use 0 for numeric types, '\0' for character types, default construction for std::string, etc. and nullptr (when available) for pointers. Mar 19, 2013 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.