字符串类型从用户获取输入'space'

String Type getting input from user with 'space'

本文关键字:space 输入 获取 类型 用户 字符串      更新时间:2023-10-16

>我正在尝试获取一个字符串处理程序,该处理程序从字符串类型变量中的用户那里获取输入...但它正在崩溃,我想知道为什么?或者我做错了什么...

 string UIconsole::getString(){
    string input;
    getline(cin,input);
    if(input.empty() == false){
        return input;
    }
    else{getString();}
    return 0;
}

编辑:错误:

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid

您有几个错误,但消息引用的特定错误是这样的:

return 0;

不能从空指针构造std::string。如果需要空字符串,请尝试以下结构之一:

return "";
return std::string();

<小时 />您的另一个错误是对getString()的递归调用。完全不清楚你想在那里做什么。也许这符合您的要求:

// untested
std::string UIconsole::getString(){
    std::string input;
    while(std::getline(std::cin, input) && input.empty()) {
        // nothing
    }
    return input;
}