C++ 将字符串解析为不同的标记
如何解析单个字符串,例如ducks hollow23!分成三种不同的代币。此字符串被读入名为input的单个字符串,需要检查其是否有效。基本上,功能与此类似:C++ 将字符串解析为不同的标记,c++,C++,如何解析单个字符串,例如ducks hollow23!分成三种不同的代币。此字符串被读入名为input的单个字符串,需要检查其是否有效。基本上,功能与此类似: int inputString(string name, string keyWord, bool trueFalse){ string input; cin >> input; // input = "ducks hollow23 !" // how to I put "ducks
int inputString(string name, string keyWord, bool trueFalse){
string input;
cin >> input;
// input = "ducks hollow23 !"
// how to I put "ducks hollow23 !" into name, keyWord, trueFalse and then
// check if name is a valid name and if keyWord is valid or if not needed, and trueFalse
// is valid
}
下面给出了一个示例代码段:
char str[] = input.c_str(); // e.g. "ducks hollow23 !"
char * pch;
pch = strtok (str," ");
string str[3];
int i = 0;
while (pch != NULL) {
if (i > 2)
break; // no more parsing, we are done
str[i++] = pch;
pch = strtok(NULL, " ");
}
// str[0] = "ducks", str[1] = "hollow23", str[2] = "!"
您的示例不公平-字符串将只是您设置中的鸭子,您可以将其解释为名称 其他>>将为您提供更多代币。您还需要引用&以获取值
int inputString(string& name, string& keyWord, bool& trueFalse) {
string flag;
cin >> input >> keyWord >> flag;
trueFalse = (flag == "!");
}
最简单的方法可能是使用istringstream
我不确定你认为有效的输入,所以我使用的唯一错误检查是,ItestIn流处于良好状态。
我已经修改了inputString以获取完整的输入字符串,您可以从cin获得该字符串你必须使用lexer。您可以使用自己的或生成的:我只想将ducks解析为name,将hollow23解析为关键字!使用strtok进行标记化,如@BillCunningham:这不是解析。
#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