0

I'm trying to cin an undefined number of coords (x,y,weight) on 1 single line. Exemple:

Please enter all the coords:

(1,2,5) (1,5,7) (2,5,2) (2,4,4) (2,3,5) (3,4,1) (4,5,9)

I will stock them in a 2d array, so for my first coord it would be something like:

array[1][2] = 5

If it was only a single coord per line, I would do something like:

cin >> trash_char >> x >> y >> weight >> trash_char;
array[x][y] = weight

How can I do that for an undetermined amount of coords on a single line?

Thanks guys!

allaire
  • 5,995
  • 3
  • 41
  • 56
  • What did you try, and how did it fail? – jxh Aug 04 '12 at 19:30
  • Right now I'm doing it for a fixed number of coords, since I'm still not sure the best way to tackle the best way... – allaire Aug 04 '12 at 19:31
  • If you can do 1 coordinate, then you can read in a line with `getline`, and split it into single coordinates. – jxh Aug 04 '12 at 19:34

2 Answers2

1

Define a struct.

struct Coord3D{
     float x,y,z;
};

Define a insertion operator

template<typename ReadFunc>
istream& operator >> (istream& stream, Coord3D& coord){
     return ReaderFunc(stream, coord );
}

Define a reader function.

istream& MyCoordReader(istream& stream, Coord3D& coord){
     char trash_char = 0;
     return stream >> trash_char >> x >> y >> weight >> trash_char;
}

Use it like so

 //template instantiation, probably wrong syntax
template<MyCoordReader> istream& opeartor >> (istream&,Coord3D&);

int main(){
   std::vector<Coord3D> coordinates;
   Coord3D coord;
   while( cin >> coord ){ coordinates.push_back(coord); }
   return 0;
}
dchhetri
  • 6,926
  • 4
  • 43
  • 56
0

Like this

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

string line;
getline(cin, line);
istringstream buffer(line);
while (buffer >> trash_char >> x >> y >> weight >> trash_char)
{
  // do something
}

use getline to read one line into a string. Then wrap that string in an istringstream so you can read the coords from that.

jahhaj
  • 3,021
  • 1
  • 15
  • 8
  • For some reason getline is not working under xcode on Mac, weird :O I can't input anything – allaire Aug 04 '12 at 19:50
  • Maybe this reason, http://stackoverflow.com/questions/1744665/need-help-with-getline. Impossible to say without seeing your code. I'd be surprised if getline really didn't work on the Mac. – jahhaj Aug 04 '12 at 19:53
  • the ws(cin); trick did it, now, only problem is it never enter the while loop :O I have the same exact code – allaire Aug 04 '12 at 20:01
  • Think I found it, it's only while(buffer) – allaire Aug 04 '12 at 20:04