简体   繁体   English

C ++用户输入字符串错误

[英]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?? 我尝试重新构建解决方案-我应该使用char数组而不是字符串作为应用程序中文本的数据容器吗?

You can not initialize a string from a NULL pointer. 您不能使用NULL指针初始化字符串。 Try: 尝试:

string userInput = "";

or simply 或简单地

string userInput;

See here and check ctor no. 看到这里并检查ctor号。 5, based on the C++ standard: 5,基于C ++标准:

21.4.2 basic_string constructors and assignment operators [string.cons] 21.4.2 basic_string构造函数和赋值运算符[string.cons]

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

8 Requires: s shall not be a null pointer. 8 要求: s不得为空指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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