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