分离输入C++; 我正在制作一个C++的文本冒险游戏。现在我得到的输入如下: string word1, word2; cin >> word1 >> word2; parse(word1, word2); string line; getline(std::cin,line); auto strings =split(line,' ');

分离输入C++; 我正在制作一个C++的文本冒险游戏。现在我得到的输入如下: string word1, word2; cin >> word1 >> word2; parse(word1, word2); string line; getline(std::cin,line); auto strings =split(line,' ');,c++,c++11,input,io,C++,C++11,Input,Io,输入示例可以是 goto store 现在,要退出,您必须键入quit和任何其他要退出的文本 如何使输入用空格分隔,并且我可以判断第二个字符串是否为空 更新 我尝试了第一个答案,但在windows上出现以下错误: The instruction at 0x00426968 referenced memory at 0x00000000. The memory could not be read. Click OK to terminate the program. 我想这就是你要找的。我

输入示例可以是

goto store
现在,要退出,您必须键入
quit
和任何其他要退出的文本

如何使输入用空格分隔,并且我可以判断第二个字符串是否为空

更新

我尝试了第一个答案,但在windows上出现以下错误:

The instruction at 0x00426968 referenced memory at 0x00000000. 
The memory could not be read.

Click OK to terminate the program.

我想这就是你要找的。我不知道解析是如何工作的,但这就是我解决问题的方法

string word1, word2;
cin >> word1;
if(word1 == "quit"){
    //quit code
}
else
    cin >> word2;

通过单独请求输入,您可以插入此if语句。该if检查输入的第一个字符串是否为“quit”,忽略第二个字符串,并运行quit代码。如果第一条输入不是“退出”,它将请求第二条输入。

使用此代码,我将整个输入放在一个名为
InputText
的字符串中,并在循环中逐字符分析它。我将字符存储在一个名为
Ch
的字符串中,以避免在将其声明为字符时显示代码而不是我的字符的常见问题。我一直在为名为
temp
的临时字符串添加字符。我有一个名为
Stage
的int,它决定我的临时字符串应该放在哪里。如果
Stage
为1,则我将其存储在
word1
中,每当我到达第一个空间时,我将
Stage
增加到2并重置温度;因此,现在开始存储在
word2
中。。如果有超过1个空格,您可以在my
开关的
default
处显示错误消息。如果只有一个单词而没有空格,您可以知道,因为我初始化了
word2=“”
,在循环之后仍然是这样

string Ch, InputText, word1 = "", word2 = "", Temp = "";
unsigned short int Stage = 1;
cin >> InputText;
for(int i = 0; i < InputText.length(); i++){
    Ch = to_string(InputText[i]);
    if (Ch == " "){
        Stage++;
        Temp = "";
    }
    else{
        switch (Stage){
        case 1:
            Temp.append(Ch);
            word1 = Temp;
            break;
        case 2:
            Temp.append(Ch);
            word2 = Temp;
            break;
        default: //User had more than 1 space in his input; Invalid input.
        }
    }
}
if (word1 == "quit" && word2 == ""){
    //Your desired code
}
字符串Ch,InputText,word1=“”,word2=“”,Temp=“”;
无符号短整型阶段=1;
cin>>输入文本;
对于(int i=0;i
检查字符串大小,你可以知道有许多单词。
如果
strings
size等于1,则第二个字符串为空。

一次读取一行,然后将其拆分为任意多个单词。参考此处拆分字符串请参阅@KevinBrown-谢谢,请稍等。我收到此错误:0x00426968处的指令引用了0x00000000处的内存。内存无法读取。单击“确定”终止程序。我已使用命名空间std
在我的文件的开头。@technokid-没关系,你的编译器会正确处理这个问题的。谢谢你的建议,我已经将它更改为更有用,这会让用户按enter键两次。我希望他们能够在一行上编写
goto store
string line;
getline(std::cin,line);
auto strings =split(line,' ');