Thread: Need Help with reading file

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    15

    Post Need Help with reading file

    OK before anyone says that this is homework, let me say that this is homework.
    I understand the question and have even written the code.
    The question is.
    Write A Program to write to a file, read from that file and get the number of lines and the number of words.

    The number of lines works every time, but the number of words works only for the last line inputted. We have not learnt vectors or using namespace std; yet so they are out of the question.


    Code:
    #include<fstream.h>
    #include<iostream.h>
    #include<conio.h>
    void main()
    {
       //Inputting text part
    
       char text[50];
       ofstream out;
       out.open("c:/country.txt",ios::app);
       cout<<"\nEnter text\n";
       cin.getline(text,50);
       out<<text<<"\n";
       out.close();
    
       //Outputting and calc text part
       ifstream inp;
       const int n=80;
       int nol=0,now=0;    //nol is number of lines and now is number of words
       char line[n],x[n];
       inp.open("c:/country.txt");
       cout<<"\nDisplay all records\n\n";
       while(inp)
       {
       inp.getline(line,80);
       cout<<line<<endl;
       nol++;
       strcpy(x,line);
       for(int i=0;i<80;i++)
       {
       	if(x[i]==' '||x[i]=='\n')
          {
          	now+=1;
          }
       }
       }
       inp.close();
       cout<<"\nTotal number of lines = "<<nol-1<<"\n";
       cout<<"\nTotal number of words = "<<now-1<<endl;
       getch();
    }
    If I skip the whole inputting text part, the program shows me the number of words in the file correctly.

    If I dont skip the inputting text part, the program shows me the number of words in the last inputted line only.

    Please tell me what I am doing wrong.


    EDIT:
    Forgot to say thanks in advance
    Last edited by aditya_t90; 11-11-2009 at 05:50 AM. Reason: Forgot to say thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM