Reading in words from a file and placing into an assorted file.

Where can I find info/techniques on bringing in words from a file so that I may place them into an assorted list. Well, placing them in an assorted list another topic that I will have to read up on but I at least want to know how to read in word by word.

I want to be able to use something like this:

1
2
3
4
5
6
7
8
9
int main(int argc,char argv[]) {

    std::string filestring = std::string(argv[1]);
    
    std::ifstream file(filename.c_str());

    string word;
    while (is >> word)
    ......


Would this be correct?
You should do
1
2
3
4
5
while(file.is_good())
{
	file >> word;
	//do stuff with the word
}
So you're suggesting I should try the following?

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(int argc,char argv[]) {

    std::string filestring = std::string(argv[1]);
    
    std::ifstream file(filename.c_str());

    string word;

    while(file.is_good())
    {
         file >> word;
         ......
    }
Or better yet something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int main(int argc,char argv[]) {

    if (argc != 2) 
    {
        std::cout << "\nERROR: Filename entered incorrectly.\n" << std::endl;
        std::cout << "Please re-run the program and enter in valid format: <filename>.txt" << std::endl;
    }
    
    std::string filestring = std::string(argv[1]);
    openFile(fileString);    
    
    return 0;
}

void openFile(std::string &filename){

    std::ifstream file(filename.c_str());

    if (!file.is_open())
    {                                                    
        std::cout << "\nCould not open file. File does not exist.\n" << std::endl;
        exit(1);
    }
    
    string word;

    while(file.is_good())
    {
         file >> word;
         ......
    }
}
I prefer the initial approach -> while (is >> word) {/*...*/} because...

1
2
3
4
5
6
7
while(file.is_good())
{
    file >> word;
    //what if !file.is_good() now?

    //...
}


Wy would you need to do anything to the file after extracting the word? The next loop checks that the stream is not good and that's that. Or am I missing something?
What about this -> //... ? You're processing the word there. If file>>word; fails you don't want to proceed.
Ahh, I see. Thanks. :)
Topic archived. No new replies allowed.