NateTheGreatt
NateTheGreatt

Reputation: 309

C++ detect space in text file

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?

Upvotes: 1

Views: 2415

Answers (1)

JoshD
JoshD

Reputation: 12814

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.

Upvotes: 9

Related Questions