我将假设整数和字符串的顺序是未知的。您可以利用cin
to bool 的转换来确定您是否检测到 int。
基本上,(cin >> intValue)
(where intValue
is an int
) 是一个表达式,true
如果接下来的几个字符构成可以放入 an 的有效数字,则返回int
,false
否则返回。同样的原则也适用于其他类型,例如string
. 这些可以在 if 语句中使用,例如
int intValue;
if (cin >> intValue) { //evaluates to true or false
// do something
} else {
// do something else
}
您可以将其与 while 循环一起使用来解析整个输入,如下所示:
vector<int> ints; //container to store ints
vector<string> strings; //container to store ints
while(true) {
int intValue;
string stringValue;
if(cin.eof()) //exit the loop when the end of the input is reached
break;
if(cin >> intValue) { //if this is true, then an int was successfully read into intValue
ints.push_back(intValue);
} else if (cin >> stringValue) { //if this is true, int could not be read but string was successfully read
strings.push_back(stringValue);
} else {
cout << "Error: unknown value read in, not recognized as int or string" << endl;
exit(-1);
}
}
编辑:
我刚刚读到您已经将该行作为字符串。上述相同的解决方案将起作用,只需使用 stringstream 而不是 cin:
string line; //the line that you already have, initialized elsewhere
stringstream ss(line.str()); //convert the line to a stringstream, treat it similar to cin
vector<int> ints; //container to store ints
vector<string> strings; //container to store strings
while(true) {
int intValue;
string stringValue;
if(ss.eof())
break;
if(ss >> intValue) {
ints.push_back(intValue);
} else if (ss >> stringValue) {
strings.push_back(stringValue);
} else {
cout << "Error: unknown value read in, not recognized as int or string" << endl;
exit(-1);
}
}
在您的示例中,即 line Move 1 to 2
,向量将包含1
and 2
,并且向量将包含Move
and to
。