如何从作为模式给出的std :: string中提取单词?

时间:2015-03-23 17:27:34

标签: c++ c++11 stdstring

考虑一下,我们有一个文本文件,它由2-D坐标逐行组成:

( 123 , 356 )

( 33 , 3158 )

( 12 , 5 )

等等。

当我们逐行扫描此文本文件时,提取x和y坐标的最佳方法是什么?

我的方法看起来并不优雅。我在std::string中获取该行,然后运行循环以提取所需的点:

void find_coordinates(std::string str, int &x, int &y) {
    int i = 2;
    std::string temp;

    while (i < str.length()) {
        if (str[i] == ' ') {
            ++i;
            continue;
        }

        else if (str[i] == ',') {
            x = std::stoi(temp);
            temp.clear();
        }

        else if (str[i] == ')') {
            y = std::stoi(temp);
            return;
        }

        else 
            temp += str[i];

        ++i;
    }
}   


std::ifstream f("file.txt");

while (getline(f, line)) {
    int x, y;
    find_coordinates(line, x, y);
}

2 个答案:

答案 0 :(得分:3)

有时最古老,最简单的解决方案是最好的解决方案:

void find_coordinates(const std::string& str, int& x, int& y)
{
    if (sscanf(str.c_str(), "( %d , %d )", &x, &y) != 2)
       throw std::runtime_error("Parsing failed");
}

live demo

如果您的格式变得更加灵活,这种方法将会失败。

答案 1 :(得分:1)

我会使用Boost tokenizer类进行这种解析。

#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main(int, char**)
{
   string text = "( 123 , 356 )";

   char_separator<char> sep("(), ");
   tokenizer< char_separator<char> > tokens(text, sep);
   BOOST_FOREACH (const string& t, tokens) {
    cout << t << "." << endl;
  }
 }

运行here

相关问题