Thread: Reading a File and returning single words

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2005
    Location
    Germany
    Posts
    12

    Reading a File and returning single words

    Hello everybody,

    My goal with this programm is to implement a function that reads a file with text, and returns successively single words, that can be handled by another function.

    One of the problems is, that for some reason it stops giving outputs at the last word and stays running instead of breaking up ( return 0; ).

    I wonder also, how could/should I implement this as a method, that throws all the words of the file, so that they can be handled by another method?

    Thanks in advance!

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    
    
    int main()
    {
    	char ch;
    	std::string word = "";
    	
    	// Givin the InputFile a more suitable name.
    	std::fstream inputFile("test.txt");
    	
    	// pointer initialisation, pointing to first character
    	FILE *fptr = fopen("test.txt", "r");
    	
    	// ch has the first character of the file
    	ch = getc( fptr );
    	
    	// Read till end of file (problem: it doesnt stop after printing the last word) 
    	while(!inputFile.eof())
    	{		
    		if ( (ch != ' ')  && (ch != '\n')  )
    		{
    			word += ch;
    			ch = getc( fptr );
    			
    			// Reading ' ' or '\n' implies the end of a word. print it.
    			if( (ch == ' ') || (ch == '\n') ) {
    				std::cout << word << std::endl;
    				word = "";
    			}
    		}
    		if( (ch == ' ') || (ch == '\n')) { 
    			ch = getc( fptr );
    		}
    		if( !((ch != ' ') || (ch == ' ')) ) {
    			ch = getc( fptr );
    		}
    	}
    	return 0;
    }
    Last edited by kapri; 05-10-2005 at 07:59 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 06-05-2009, 09:42 AM
  2. fopen returning "Bad File Pointer"
    By jprukop in forum C Programming
    Replies: 4
    Last Post: 04-17-2009, 03:01 PM
  3. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. reading in array and returning length
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 04-21-2002, 09:25 PM