最简单的方法可能是使用istringstream
。
我不确定你认为什么是有效输入,所以我唯一使用的错误检查是istringstream
处于良好状态。
我修改了inputString()
以获取全部输入string
,您将从cin
获得。
#include <iostream>
#include <sstream> // for std::istringstream
using namespace std;
// Note call by reference for the three last parameters
// so you get the modified values
int inputString(string input, string &name, string &keyWord, bool &trueFalse){
std::istringstream iss(input); // put input into stringstream
// String for third token (the bool)
string boolString;
iss >> name; // first token
// Check for error (iss evaluates to false)
if (!iss) return -1;
iss >> keyWord; // second token
// Check for error (iss evaluates to false)
if (!iss) return -1;
iss >> boolString; // third token
// Check for error (iss evaluates to false)
if (!iss) return -1;
if (boolString == "!") trueFalse = false;
else trueFalse = true;
return 0;
}
int main() {
string input, name, keyWord;
bool trueFalse;
//cin << input;
// For this example I'll just input the string
// directly into the source
input = "ducks hollow23 !";
int result = inputString(input, name, keyWord, trueFalse);
// Print results
cout << "name = " << name << endl;
cout << "keyWord = " << keyWord << endl;
// Use std::boolalpha to print "true" or "false"
// instead of "0" or "1"
cout << "bool result = " << boolalpha << trueFalse << endl;
return result;
}
输出是
name = ducks
keyWord = hollow23
bool result = false
你必须使用一个词法分析器。您可以使用您自己的或生成的:https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Code+Generation+Targets – ibre5041 2014-09-25 18:05:49
我只是想将“duck23”分解成keyWord的名字“hollow23”!成truefalse – 2014-09-25 18:14:37
使用strtok来标记,如http://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c – 2014-09-25 18:23:23