-
Parsing Data in C++
hola amigos. this is my goal, i'm reading a file into my program, each line resembles this (its for a graph project)
SOUCE : VertexA 1 VertexB 13 VertexC 8
where souce is the source vertex and the vertecies after the colon are adjacent vertecies. i am using getline to pull in each line of my input file. then i redirect each 'thing' into a string and the costs into an integer.. fine so long as i don't have more than one vertex after the source, how do i loop to run through til the end of the getline and then pull another line up after that?
code reads as this so far
Code:
while( getline(in, oneLine) )
{
string source, colon, dest;
int cost;
in >> source;
in >> colon;//colon fall through
//HERE I Want to run my loop til oneLine is gone, but how??
while(oneLine){//THIS CAUSES ERRORS in G++
in>>dest;
in>>cost;
}//closes while one line
}//closes getline while loop
this is obviously only to parse the input file and nothign more.. so any/all advice is appreciated.
-
You could do something like -
Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class vertices
{
private:
class vertex
{
private:
string name;
int val;
friend istream& operator >>(istream& is, vertex& ve)
{
return is >> ve.name >> ve.val;
}
friend ostream& operator <<(ostream& os, const vertex& ve)
{
return os << ve.name << ' ' << ve.val;
}
};
vertex source;
vertex adj[2];
friend istream& operator >>(istream& is,vertices& ve)
{
string line;
getline(is,line);
stringstream ss;
ss << line;
string discard;
ss >> discard >> discard >> ve.source >> ve.adj[0] >> ve.adj[1];
return is;
}
friend ostream& operator <<(ostream& os, const vertices& ve)
{
return os << ve.source << ' ' << ve.adj[0] << ' ' << ve.adj[1];
}
};
int main()
{
vertices v;
cin >> v;
cout << v << '\n';
return 0;
}