分隔输入C++
Separating input C++
我正在用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
}
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type