你可以做这样的事情,需要#include <sstream>:
char trash;
std::stringstream mystream(myInputString);
mystream >> team1 >> goalst1 >> trash>> goalst2 >> team2;
或
char trash;
std::stringstream mystream;
mystream << myInputString;
mystream >> team1 >> goalst1 >> trash>> goalst2 >> team2;
编辑:这是更高级但有点整洁。将其粘贴在标题中:
#include <iostream>
#include <string>
#include <array>
#include <cstring>
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&sliteral)[N]) {
std::array<e, N-1> buffer; //get buffer
in >> buffer[0]; //skips whitespace
if (N>2)
in.read(&buffer[1], N-2); //read the rest
if (strncmp(&buffer[0], sliteral, N-1)) //if it failed
in.setstate(in.rdstate() | std::ios::badbit); //set the state
return in;
}
template<class e, class t>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e& cliteral) {
e buffer; //get buffer
in >> buffer; //read data
if (buffer != cliteral) //if it failed
in.setstate(in.rdstate() | std::ios::badbit); //set the state
return in;
}
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, e(&carray)[N]) {
return std::operator>>(in, carray);
}
template<class e, class t, class a>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, a& obj) {
return in >> obj; //read data
}
这允许您在流中执行字符串文字:
std::stringstream mystream(myInputString);
mystream >> team1 >> goalst1 >> '-' >> goalst2 >> team2;
或
std::stringstream mystream;
mystream << myInputString;
mystream >> team1 >> goalst1 >> '-' >> goalst2 >> team2;
另请参阅:Safer but easy-to-use and flexible C++ alternative to sscanf()