Search code examples
c++multiple-columnsreadfileskip

C++ read file line by line and some lines have different columns than the others


My text.txt looks like this:

1   52  Hayden Smith        18:16   15  M   Berlin
2   54  Mark Puleo          18:25   15  M   Berlin
3   97  Peter Warrington    18:26   29  M   New haven
4   305 Matt Kasprzak       18:53   33  M   Falls Church
5   272 Kevin Solar         19:17   16  M   Sterling
6   394 Daniel Sullivan     19:35   26  M   Sterling
7   42  Kevan DuPont        19:58   18  M   Boylston
8   306 Chris Goethert      20:00   43  M   Falls Church

The problem is, for line three, the name of town is New Haven, there is a space between New and haven. And also for line four, there is a space between Falls and Church. This creates a problem when I read the file line by line.

So, my code looks like this:

ifstream infile("text.txt", ios::in);
if(!infile)
{
    cerr<<"File could not be opend"<<endl;
}

SortedLinked mylist;

int a;
int b;
string c;
string d;             // I have eight different variables, representing
string e;             // each column, but some lines have nine columns.
int f;                   
char g;
string h;

string mystr;
int mymin;
int mysec;

while(infile>>a>>b>>c>>d>>e>>f>>g>>h)
{

   // This does not work, because as you get to line three, h is New, there
   // is no variable to store Haven. Therefore my code can only get to line 
   // 3. 

    mystr = c+d;
    mymin = convertString<int>(e.substr(0,2));
    mysec = convertString<int>(e.substr(3, 4));


    Runner M(mystr, f, mymin, mysec);
    //M.print();
    mylist.additem(M);


}

Also, if you try to do something like this:

replace(h.begin(), h.end(), ' ', '_')

try to fill a underscore between New and haven, it will not work. because this attempts to replace a variable with another, h in here is New, it is not New haven, you cannot get to haven, because haven is another variable. So there is no way for you to replace a space with a underscore.

Also, if you try to do something like this:

while(infile>>a>>b>>c>>d>>e>>f>>g>>h>>i)

This also does not work, because when you get to line 1, there are only right columns, there is nothing to store into variable i. Code like this will only get you to line 1.

if you have some other way to do this, like skipping town name column, column 8 and column 9 (for some lines), because i don't even need the name of town.

Or, you can get rid of the space between New haven and the space between Fall Church. Anything would be appreciated.


Solution

  • You can use getline to read rest of the line.

    while( (infile>>a>>b>>c>>d>>e>>f>>g) && getline(infile, h))