C++ Splitting the input problem

那年仲夏 提交于 2019-12-24 10:20:07

问题


I am being given input in the form of:

(8,7,15)
(0,0,1) (0,3,2) (0,6,3)
(1,0,4) (1,1,5)
(2,1,6) (2,2,7) (2,5,8)
(3,0,9) (3,3,10) (3,4,11) (3,5,12)
(4,1,13) (4,4,14)
(7,6,15)

where I have to remember the amount of triples there are. I wrote a quick testing program to try read the input from cin and then split string up to get the numbers out of the input. The program doesn't seem to read all the lines, it stops after (1,1,5) and prints out a random 7 afterwards

I created this quick testing function for one of the functions I am trying to create for my assignment:

int main ()
{
  string line;
  char * parse;

  while (getline(cin, line)) {

    char * writable = new char[line.size() + 1];
    copy (line.begin(), line.end(), writable);
    parse = strtok (writable," (,)");

    while (parse != NULL)
    {
      cout << parse << endl;
      parse = strtok (NULL," (,)");
      cout << parse << endl;
      parse = strtok (NULL," (,)");
      cout << parse << endl;
      parse = strtok (NULL," (,)");
    }

  }
  return 0;
}

Can someone help me fix my code or give me a working sample?


回答1:


You can use this simple function:

istream& read3(int& a, int& b, int& c, istream& stream = cin) {
    stream.ignore(INT_MAX, '(');
    stream >> a;
    stream.ignore(INT_MAX, ',');
    stream >> b;
    stream.ignore(INT_MAX, ',');
    stream >> c;
    stream.ignore(INT_MAX, ')');

    return stream;
 }

It expects the stream to start at a (, so it skips any characters and stops after the first ( it sees. It reads in an int into a which is passed by reference (so the outside a is affected by this) and then reads up to and skips the first comma it sees. Wash, rinse, repeat. Then after reading the third int in, it skips the closing ), so it is ready to do it again.

It also returns an istream& which has operator bool overloaded to return false when the stream is at its end, which is what breaks the while loop in the example.

You use it like this:

// don't forget the appropriate headers...
#include <iostream>
#include <sstream>
#include <string>

int a, b, c;

while (read3(a, b, c)) {
    cout << a << ' ' << b << ' ' << c << endl;
}

That prints:

8 7 15
0 0 1
0 3 2
0 6 3
1 0 4
1 1 5
2 1 6
2 2 7
2 5 8
3 0 9
3 3 10
3 4 11
3 5 12
4 1 13
4 4 14
7 6 15

When you give it your input.

Because this is an assignment, I leave it to you to add error handling, etc.




回答2:


I've written a blog 9 days back exactly to parse such inputs:

  • Playing around with Boost.Spirit - Parsing integer triplets

And you can see the output here for your input : http://ideone.com/qr4DA



来源:https://stackoverflow.com/questions/7238700/c-splitting-the-input-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!