2014-09-25 51 views
0

如何解析单个字符串,如“ducks hollow23!”分成三个不同的标记。该字符串被读入一个称为输入的字符串,如果它有效,则需要检查。基本上,功能类似于此:将字符串解析为不同的标记

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 

} 
+0

你必须使用一个词法分析器。您可以使用您自己的或生成的:https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Code+Generation+Targets – ibre5041 2014-09-25 18:05:49

+0

我只是想将“duck23”分解成keyWord的名字“hollow23”!成truefalse – 2014-09-25 18:14:37

+0

使用strtok来标记,如http://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c – 2014-09-25 18:23:23

回答

0

的示例代码片段如下:

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] = "!" 
0

你的例子是不公平的 - 字符串会在你的设置,只是“鸭子”,你可以解释为名称 其他>>会给你更多的令牌。你也需要引用&得到值回

int inputString(string& name, string& keyWord, bool& trueFalse) { 
    string flag; 
    cin >> input >> keyWord >> flag; 
    trueFalse = (flag == "!"); 
} 
0

最简单的方法可能是使用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