0

可能重复:
如何在 C++ 中拆分字符串?
C++ 拆分字符串

如何在 C++ 中从文件中拆分一行,如下所示?

我想保存具有以下格式的游戏输出结果:

CFC 1 - 0 RES

我有四个变量:

string team1;
string team2;
int goalst1;
int goalst2;

如何拆分字符串,使每个对应部分都在上述四个变量中?

4

4 回答 4

5
string team1;
string team2;
int goalst1;
int goalst2;
string dash;
std::cin >> team1 >> goalst1 >> dash >> goalst2 >> team2;
于 2012-07-14T04:24:00.043 回答
3

你可以做这样的事情,这需要#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;

另请参阅:sscanf() 的更安全但易于使用且灵活的 C++ 替代方案

于 2012-07-14T04:23:57.360 回答
1

如果我做对了,您可能正在尝试从文件中读取。然后使用 ifstream,您可以像从 cin 这样的标准输入中读取文件一样读取文件。

IE

  ifstream myfile("filename");

现在使用 myfile 而不是 cin 运算符,你就完成了..

于 2012-07-14T04:27:48.923 回答
0

我喜欢boost::split这样的工作:

#include <string>
#include <vector>

#include <boost/algorithm/string/split.hpp>

struct Result {
     std::string team1;
     std::string team2;
     unsigned goals1;
     unsigned goals2;
};

Result split(std::string const& s) {
    std::vector<std::string> splitted;
    boost::split(s, splitted, boost::token_compress_on);

    if (splitted.at(2) != "-") {
        throw runtime_error("The string format does not match");
    }

    Result r;
    r.team1 = splitted.at(0);
    r.team2 = splitted.at(4);
    r.goals1 = stoi(splitted.at(1));
    r.goals2 = stoi(splitted.at(3));

    return r;
}
于 2012-07-14T15:16:12.680 回答