program only reads first word

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


using namespace std;

int main()
{
    string word;
    ifstream infile("worm.txt");
    infile >> word;
    cout << word << endl;
    infile.close();

}


in the file it says:
I like pie
I like rice
and I like applesauce

My issue is that the code only reads the first word "I" without reading everything else. What do I need to change for the code to read the entire file?
What you do is what you get.:) You are reading only one word. You should use function std::getline in a loop while end of file will not be encountered.
Or you can read word by word as you a re doing but in a loop.
The extraction operator >> skips all leading whitespace and halts reading as soon as it encounters whitespace. Like vlad mentioned, you should use a loop to read the file line by line. Take a look at this pseudocode for an idea:

while end of file is not reached:
read a word
do something with the word
ohh ok!!

@ maese909
so it would be 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
#include <iostream>
#include <fstream>
#include <string>


using namespace std;

int main()
{
    ifstream wormfile("worm.txt");
    string wormline;

while (!wormfile)
{
getline(wormfile, wormline);
cout << wormline << endl;
}

    wormfile.close();
    return 0;

}


I'm not too good with while loops so I think thats where I messed up because when I try to put it in my code it compiles but it doesn't print any word.

I know something is up with the while loop but i'm not sure what it is because it compiles.
Last edited on
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>


using namespace std;

int main()
{
    ifstream wormfile("worm.txt");
    string wormline;

while (!wormfile.eof())
{
getline(wormfile, wormline);
cout << wormline << endl;
}

    wormfile.close();
    return 0;

}


ah.. I found out the issue! it needed .eof() at the end.. not sure what that means exactly, but now I know i need to add it...
End of line
End of Record
End of file

EOF is just a predefined function that looks to see
whether the file pointer is at ( or with "C", PAST ) the end of the file.
EOF()

If it is, then things crash,
unless you check for this condition
and have the code do something about it first, like stop,
before the program fills your hard drive with very odd stuff
- like zero's.

WHILE your pointer is NOT EOF() then things are considered OK.

Last edited on
Don't loop on EOF.

13
14
15
16
  while (getline(wormfile,wormline))
  {
    cout << wormline << endl;
  }

Please use consistent indentation.

Hope this helps.
Topic archived. No new replies allowed.