当我尝试将用户输入作为字符串获取时,出现了一个奇怪的错误。
我有正确的包含;
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
这是代码,执行时出现错误;
write("Enter your name");
string name = readString();
write(name);
上面的代码调用了这两个函数;
void game::write(std::string message)
{
cout << message << "\n";
}
string game::readString()
{
string userInput = NULL;
std::cin >> userInput;
return userInput;
}
这是我得到的错误:
我已尝试重新构建解决方案 - 我是否应该使用字符数组而不是字符串作为应用程序中文本的数据容器?
最佳答案
您不能从 NULL
指针初始化字符串。尝试:
string userInput = "";
或者只是
string userInput;
参见 here并检查 ctor 号5、基于C++标准:
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.
关于C++ 用户输入字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15506275/