分隔输入C++

Separating input C++

本文关键字:C++ 输入 分隔      更新时间:2023-10-16

我正在用C++制作一款文字冒险游戏。现在我得到这样的输入:

string word1, word2;
cin >> word1 >> word2;
parse(word1, word2);

示例输入可以是

goto store

现在,要退出,您必须键入quit和任何其他文本才能退出。

我怎样才能使输入被空格分隔,我可以判断第二个字符串是否为空。

更新

我尝试了第一个答案,但在Windows上收到此错误:

The instruction at 0x00426968 referenced memory at 0x00000000. 
The memory could not be read.
Click OK to terminate the program.
 #include <vector>
 #include <string>
 #include <sstream>
 std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
        std::stringstream ss(s);
        std::string item;
        while (std::getline(ss, item, delim)) {
            if(!item.empty()) //item not elems
            elems.push_back(item);
        }
        return elems;
    }

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

该函数std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)可以使用用户定义的分隔符拆分字符串,并将每个字符串存储到向量中。请注意,如果分隔的字符串为空,则它不会加入字符串数组。

这个函数std::vector<std::string> split(const std::string &s, char delim)是最后一个函数包装器之一,所以你只需要传递两个参数,方便你使用。

像这样使用拆分函数:

string line;
getline(std::cin,line);
auto strings =split(line,' ');

检查字符串大小,您可以知道很多单词。如果大小等于 1 strings则第二个字符串为空。

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

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

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

使用此代码,我将整个输入放入一个名为 InputText 的字符串中,并在循环中逐个字符地分析它。我将字符存储在一个名为 Ch 的字符串中,以避免在将其声明为 char 时显示 ASCII 代码而不是我的字符的常见问题。我一直将字符附加到名为 Temp 的临时字符串中。我有一个名为 Stage 的 int,它决定了我的临时字符串应该去哪里。如果Stage为 1,那么我将其存储在 word1 中,每当我到达第一个空间时,我都会将Stage增加到 2 并重置温度;因此现在开始存储在word2中..如果有超过 1 个空格,您可以在我的switch 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
}