繁体   English   中英

C ++解析输入

[英]C++ parse input

我需要解析一个看起来像这样的C ++ stdin输入:

NM(成对)

0 0
2 1 (0,1)
2 0
5 8 (0,1) (1,3) (2,3) (0,2) (0,1) (2,3) (2,4) (2,4)

如果N> 0 && M> 0,则将跟随M对。 它是单行输入,所以我不知道该怎么做。

我有一些解决方案,但是有什么告诉我这不是最好的解决方案。

void input(){
    int a[100][2];
    int n,m;
    char ch;
    cin >> n >> m;
    for ( int i = 0; i < m; i++) {
        cin >> ch >> a[i][0]>> ch>> a[i][1]>>ch;    
    }

    cout << n << " " << m << " \n";

    for ( int i=0; i < m; i++ ) {
        cout << "(" << a[i][0] << " ," << a[i][1] << ")";   
    }
}

我的问题是最好/更正确的方法是什么?

由于无法信任应用程序的输入数据,因此添加错误检查以确保提供的数据确实有效非常重要(否则,应用程序的结果在解析时可能会出错)。

处理诸如此类的错误的“ C ++方法”是在负责解析数据的函数中出现问题时引发异常。

然后,此函数的调用方会将调用包装在try-catch-block中,以捕获可能出现的错误。


使用用户定义的类型 ..

定义自己的类型来保存数据对将极大地提高代码的可读性,以下实现的输出与本文后面的内容相同。

#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>

struct Pair {
  Pair (int a, int b)
    : value1 (a), value2 (b)
  {}

  static Pair read_from (std::istream& s) {
    int value1, value2;

    if ((s >> std::ws).peek () != '(' || !s.ignore () || !(s >> value1))
      throw std::runtime_error ("unexpected tokens; expected -> (, <value1>");

    if ((s >> std::ws).peek () != ',' || !s.ignore () || !(s >> value2))
      throw std::runtime_error ("unexpected tokens; expected -> , <value2>");

    if ((s >> std::ws).peek () != ')' || !s.ignore ())
      throw std::runtime_error ("unexpected token;expected -> )");

    return Pair (value1,value2);
  }

  int value1, value2;
};

我注意到,程序员可能难以理解的一件事是使用s >> std::ws ; 它用于消耗可用的空白,因此我们可以使用.peek获取下一个可用的非空白字符。

我之所以实现静态函数read_from而不是ostream& operator>>(ostream&, Pair&)是,后者将要求我们甚至在从流中读取之前都创建一个对象,这在某些情况下是不可取的。

void
parse_data () {
  std::string line;

  while (std::getline (std::cin, line)) {
    std::istringstream iss (line);
    int N, M;

    if (!(iss >> N >> M))
      throw "unable to read N or M";
    else
      std::cerr << "N = " << N << ", M = " << M << "\n";

    for (int i =0; i < M; ++i) {
      Pair data = Pair::read_from (iss);

      std::cerr << "\tvalue1 = " << data.value1 << ", ";
      std::cerr << "\tvalue2 = " << data.value2 << "\n";
    }
  }
}

通常,我不建议仅使用大写字母来命名非常量变量,而是要更清楚地表明哪个变量包含与您对输入的描述相同的名称。

int
main (int argc, char *argv[])
{
  try {
    parse_data ();

  } catch (std::exception& e) {
    std::cerr << e.what () << "\n";
  }
}

不使用用户定义的类型

解析数据以及检查错误的直接方法是使用以下内容,尽管可以通过使用“ 用户定义的对象”和运算符重载来大大改进。

  1. 使用std :: getline读取每一行
  2. 构造n std :: istringstream iss(line)并读取行
  3. 尝试使用iss >> N >> M读取两个整数
  4. 使用带有iss >> s1的std :: string s1 *读取M个 “单词”
    1. 使用s1作为初始化程序构造一个std :: istringstream inner_iss
    2. 偷看下一个可用的字符是( &&忽略此字符
    3. 读取整数
    4. 偷看下一个可用的字符是, &&忽略此字符
    5. 读取整数
    6. 偷看下一个可用的字符是) &&忽略此字符

如果在第4步之后字符串流不为空,或者iss.good()在步骤之间的任何地方返回false,则为读取的数据中的语法错误。


实施范例

可以通过以下链接找到源(将代码放在其他地方以节省空间):

N = 0, M = 0
N = 2, M = 1
     value1 = 0, value2 = 1
N = 2, M = 0
N = 5, M = 8
     value1 = 0, value2 = 1
     value1 = 1, value2 = 3
     value1 = 2, value2 = 3
     value1 = 0, value2 = 2
     value1 = 0, value2 = 1
     value1 = 2, value2 = 3
     value1 = 2, value2 = 4
     value1 = 2, value2 = 4

如果要求操作的数据全部在一行上,则最好的技术可能是将行读入字符串,然后解析从输入字符串初始化的字符串流。

您应该考虑是否需要验证括号和逗号是否真的是括号和逗号-如果输入为:

23 2 @3;8= %      7      %     12     %

您的代码目前将其视为有效。

诸如此类的规范解决方案是为这些对定义一个类型,并为其实现>>运算符。 就像是:

class Pair
{
    int first;
    int second;
public:
    Pair( int first, int second );
    //  ...
};

std::istream&
operator>>( std::istream& source, Pair& object )
{
    char open;
    char separ;
    char close;
    int first;
    int second;
    if ( source >> open >> first >> separ >> second >> close
            && open == '(' && separ == ',' && close == ')' ) {
        object = Pair( first, second );
    } else {
        source.setstate( std::ios_base::failbit );
    }
    return source;
}

鉴于此,要读取文件:

std::string line;
while ( std::getline( source, line ) ) {
    std::istringstream l( line );
    int n;
    int m;
    std::vector<Pair> pairs;
    l >> n >> m;
    if ( !l ) {
        //  Syntax error...
    }
    Pair p;
    while ( l >> p ) {
        pairs.push_back( p );
    }
    if ( ! l.eof() ) {
        //  Error encountered somewhere...
    }
    //  Other consistency checks...
}

我更喜欢Boost.Spirit来完成以下任务:

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>

#include <boost/fusion/include/std_pair.hpp>

#include <string>
#include <iostream>

struct input {
  int x, y;
  typedef std::pair<int, int> pair;
  std::vector< pair > pairs;
};

BOOST_FUSION_ADAPT_STRUCT(
  input,
  (int, x)
  (int, y)
  (std::vector< input::pair >, pairs))

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

template<typename Iterator>
struct input_parser : qi::grammar<Iterator, input(), ascii::space_type> {
  input_parser() : input_parser::base_type(start) {
    // two integers followed by a possibly empty list of pairs
    start = qi::int_ >> qi::int_ >> *pair;
    // a tuple delimited by braces and values separated by comma
    pair = '(' >> qi::int_ >> ',' >> qi::int_ >> ')';
  }

  qi::rule<Iterator, input(), ascii::space_type> start;
  qi::rule<Iterator, input::pair(), ascii::space_type> pair;
};

template<typename Iterator>
void parse_and_print(Iterator begin, Iterator end) {
    input x;
    input_parser<Iterator> p;
    bool r = qi::phrase_parse(begin, end, p, ascii::space, x);
    if(!r) {
      std::cerr << "Error parsing" << std::endl;
      return;
    }

    std::cout << "Output" << std::endl;
    std::cout << "x: " << x.x << std::endl;
    std::cout << "y: " << x.y << std::endl;
    if(x.pairs.empty()) {
      std::cout << "No pairs.";
    } else {
      for(std::vector<input::pair>::iterator it = x.pairs.begin(); 
          it != x.pairs.end(); ++it) { 
        std::cout << "(" << it->first << ',' << it->second << ") ";
      }
    }
    std::cout << std::endl;
}


int main()
{
    namespace qi = boost::spirit::qi;

    std::string input1 = "0 0";
    std::string input2 = "2 1 (0,1)";
    std::string input3 = "2 0";
    std::string input4 = "5 8 (0,1) (1,3) (2,3) (0,2) (0,1) (2,3) (2,4) (2,4)";
    parse_and_print(input1.begin(), input1.end());
    parse_and_print(input2.begin(), input2.end());
    parse_and_print(input3.begin(), input3.end());
    parse_and_print(input4.begin(), input4.end());
    return 0;
}

既然您已经注意到输入中的模式,那么像字符串标记器之类的东西都可以解决您的问题。

为此,您可以使用strtok函数。 另外对于Boost库的实现很有用,并在此处得到了很好的示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM