ifstream question

hi, i was wondering if it's possible to use ifstream to read a file and ignore a X number of words.

i.e: say i have a text file with the words

"Hello Mr. John Galt."

and I want to use the words "John" and "Galt" in my program using string?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <string>

int main()
{
 string firstName;
 string lastName;

 ifstream textFile;
 textFile.open("galt.dat")

 // what code do i use here to ignore "Hello" and "Mr."?
 // do i use cin.ignore/cin.get here?

 textFile >> firstName;
 textFile >> lastName;

 cout << "Hello Mr. " << firstName << ' ' << lastName << ".\n";
 return 0;
}


i know this a lame example but it kind of gives you an idea as to what i'm going for ):

i heard that it's possible to do this using char, a c based solution, but i'm not too familiar with it. any help is greatly appreciated.
closed account (S6k9GNh0)
http://www.cplusplus.com/reference/iostream/istream/read/

The most straight forward way is to simply read the entire file into memory and parse the data all together.
isn't that a bit inefficient?
closed account (S6k9GNh0)
Why would it be inefficient?

Reading a file bit by bit isn't efficient if you're eventually going to read the entire thing anyways. More often than not, you'll have to read the entire file anyways to know what's useless and what's not.

It's also easier to think about. You read in a file of data into memory. You feed that data to a function as input which should parse and spit out useful data at you as output (then optionally feed that output to various other functions). Then you can use that data however you want.
Last edited on
n/m that last response. however, i'm still a bit a lost from the link and i have yet to do parsing.

edit: i'm still lost o.0; the only possible alternative i've thought of is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>

int main()
{
 string junk;
 string firstName;
 string lastName;

 ifstream textFile;
 textFile.open("galt.dat")

 textFile >> junk;
 textFile >> junk;
 textFile >> firstName;
 textFile >> lastName;

 cout << "Hello Mr. " << firstName << ' ' << lastName << ".\n";
 textFile.close();
 return 0;
}


i guess this works, but something about it doesn't seem right. iow, i figured there to be a more standard based solution.
Last edited on
bump for the edit
I'd say if you file is actually suitable for streams then why not using streams.

I find your solution ok. It reflects the format of the file. So why not. To ignore x words you may use a loop.

You can also write it like so: textFile >> junk >> junk >> firstName >> lastName;
Last edited on
thanks for the help, but it seems that i have ran into a new problem. this issue is resolved but i'll have to start a new topic for my next question.
Topic archived. No new replies allowed.