Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read word by word from file in C++

Tags:

this function should read a file word by word and it does work till the last word, where the run stops

void readFile(  ) {     ifstream file;     file.open ("program.txt");     string word;     char x ;     word.clear();      while ( ! file.eof() )     {         x = file.get();          while ( x != ' ' )         {             word = word + x;             x = file.get();         }              cout<< word <<endl;             word.clear();      } } 

any one see what is the problem and how it can be solved??

like image 766
M.Tamimi Avatar asked Dec 04 '13 10:12

M.Tamimi


People also ask

How do I read a text file from word in C?

Steps To Read A File:Open a file using the function fopen() and store the reference of the file in a FILE pointer. Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread(). File close the file using the function fclose().

Which function should be used to read the file word by word?

we have to use the file input stream to read file contents. The file stream will open the file by using file name, then using FileStream, load each word and store it into a variable called word.

How read a string from a file in C++?

Call open() method to open a file “tpoint. txt” to perform read operation using object newfile. If file is open then Declare a string “tp”. Read all data of file object newfile using getline() method and put it into the string tp.


1 Answers

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word; while (file >> word) {     ... } 
like image 95
Some programmer dude Avatar answered Sep 19 '22 21:09

Some programmer dude