用C ++拆分字符串

时间:2012-07-14 04:20:51

标签: c++ string split

  

可能重复:
  How to split a string in C++?
  C++ split string

如何从文件中拆分C ++中的行(如下所示)?

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

CFC 1 - 0 RES

我有四个变量:

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

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

4 个答案:

答案 0 :(得分:5)

string team1;
string team2;
int goalst1;
int goalst2;
string dash;
std::cin >> team1 >> goalst1 >> dash >> goalst2 >> team2;

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

另请参阅:Safer but easy-to-use and flexible C++ alternative to sscanf()

答案 2 :(得分:1)

如果我做对了,你可能正试图从文件中读取。然后使用ifstream,你可以从文件中读取,就像你从cin等标准输入中读取一样。

  ifstream myfile("filename");

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

答案 3 :(得分: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;
}