将字符串解析为不同的标记

时间:2014-09-25 18:02:08

标签: c++

如何解析单个字符串,例如“ducks hollow23!”分成三个不同的代币。该字符串被读入一个名为input的字符串,如果有效则需要进行检查。基本上,功能类似于:

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

}

3 个答案:

答案 0 :(得分: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] = "!"

答案 1 :(得分:0)

你的例子不公平 - 字符串在你的设置中只是“鸭子”,你可以将其解释为名称 其他>>会为您提供更多代币。您还需要参考&来获取值

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

答案 2 :(得分: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