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

标签 c++ stl

当我尝试将用户输入作为字符串获取时,出现了一个奇怪的错误。

我有正确的包含;

#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;
}

这是我得到的错误: C++ Error

我已尝试重新构建解决方案 - 我是否应该使用字符数组而不是字符串作为应用程序中文本的数据容器?

最佳答案

您不能从 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/

相关文章:

c++ - 指向数组的指针 - 初始化元素

c++ - STL:为 vector 写入 "where"运算符

c++ - 为字符串 vector 预分配内存(C++ vector<string>)

c++ - C++中的哈希表/无序映射

c++ - 重载 += 运算符

c++ - 确定方法是否为纯虚拟 (c++)

C++ 错误 : field has incomplete type - declaring it's own class object

c++ - 用于折叠 C++ 代码的 Visual Studio 插件

c++ - 判断vector是否有重复

c++ - 使用STL c++使用绝对值对数字进行排序