SNpn
SNpn

Reputation: 2207

C++ Splitting the input problem

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?

Upvotes: 1

Views: 698

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75130

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.

Upvotes: 3

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

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

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

Upvotes: 1

Related Questions