views:

70

answers:

1

How can I go about detecting a space OR another specific character/symbol in one line of a file using the fstream library?

For example, the text file would look like this:

Dog Rover
Cat Whiskers
Pig Snort

I need the first word to go into one variable, and the second word to go into another separate variable. This should happen for every line in the text file.

Any suggestions?

+9  A: 

This is pretty simple.

string a;
string b;
ifstream fin("bob.txt");

fin >> a;
fin >> b;

If that's not quite what you want, please elaborate your question.

Perhaps a better way overall is to use a vector of strings...

vector<string> v;
string tmp;
ifstream fin("bob.txt");
while(fin >> tmp)
  v.push_back(tmp);

This will give you a vector v that holds all the words in your file.

JoshD
The first and second words on the same line. The first word on the first line needs to go into one variable, and then the second word on that line needs to go into another variable. This would be done for each line. I'm trying to learn how to do some simple file parsing.
NateTheGreatt
@NateTheGreatt By default `ifstream` will read up to whitespace, so if your files had lines like `hello there`, reading the stream the first time will read `hello`. JoshD's seems like it does exactly what you want, and you would probably want to wrap a loop around it to continue reading.
birryree
Oh jeez I didn't know that >.>. Sorry about that, and thanks for clearing that up!
NateTheGreatt
You can also define `struct line {string first; string last;};` and make a vector of these structures instead of a vector of strings. Create a new structure instance, read the two strings on that line into `first` and `last`, and then `push_back` that structure onto the vector. That will give you one vector entry per line and will still let you access the strings individually.
bta