Reputation: 403
My text file look 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
9 262 James Sullivan 20:12 28 M Sterling
10 348 Bill Gaudere 20:17 54 M Hudson
11 13 Travis Wheeler 20:23 31 M Clinton
12 69 Eric Anderson 20:34 54 M Clinton
13 341 Alex Teixeira 20:46 0 M Clinton
14 112 James Long 20:50 38 M 0
15 279 Nate Richards 21:31 17 M Berlin
......................................................
There are eight columns, separated by 'tabs', except the first name and last name is separated by a space.
I must have eight different types of variables.
int a;
int b;
string c;
string d;
string e;
int f;
char g;
string h;
I need to read the file line by line and cout every line's a, b, c, d, e, f. I also need those variables for later use.
So, I tried this:
std::ifstream infile("text.txt");
int a;
int b;
string c;
string d;
string e;
int f;
char g;
string h;
while(infile>>a>>b>>c>>d>>e>>f>>g>>h)
{
cout <<"C is: "<<c<<endl; // just to see if the loop is working.
}
I don't need arrays and vectors to store those variables, I have a linked structure. Right now, I just need a way to read the file and store those strings and integers into variables. But it's not working, lol. Don't know why. I also thought about using getline, something like this:
while(getline(infield, s)):
But, isn't this essentially just giving me one big fat line, with all strings and integers smashed together.
Upvotes: 2
Views: 5184
Reputation: 496
Your approach works exactly as you want it to when testing it on my machine, except for the fact that it will stop at the third entry:
3 97 Peter Warrington 18:26 29 M New haven
This is because of the space in New haven
, which will fail the while condition as it fails to be copied into the integer field, a
on the next iteration. If you want to keep this structure, perhaps put underscores in place of spaces. Otherwise move to parsing it line by line, perhaps with the std::regex
library.
For example, changing the location string to be seperated by underscores instead of spaces results in finding all 15 entries. To change the underscores back into spaces we can use std::replace
, so the body of your while loop would look lile:
std::cout <<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" "<<f<<" "<<g<<" ";
std::replace( h.begin(), h.end(), '_', ' ' );
std::cout<<h<<"\n";
(make sure to include algorithm
)
We now have all our entires printed!
To directly answer your original question, I'm guessing the file doesn't exist.
std::ifstream infile("text.txt");
if(!infile.is_open()) {
std::cout<<"Couldn't find file";
return 0;
}
// ..
Upvotes: 2