• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Help with C++

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

scap

Member
Joined
Jul 25, 2001
Location
Austin, tx, usa
i have two problems with some programs i have to write for class. The prompt for the problem is
Write a program that prompts the user for the name of a text file and reports the number of characters in the text file and the number of end line characters in the file.
ia m having trobble with the end line part if somone could better explain to me ofstream.h and maybe even show me a sample of how to do this it would be apperciated.
here is my code:
#include <iostream.h>
#include <fstream.h>





char name;

main()
{

long count = 0;
long total = 0;
long count2 = 0;
long total2 = 0;

char y ;
char x ;
char name[500];
ifstream infile;
cout<< "enter the name of a text file:" <<" ";
cin.get(name, 500);


infile.open(name,ios::in);


{
do
{
infile >> x;
if(!infile.eof())
{
count ++;




}

if (count>total);
{
total=count;

}

}while (!infile.eof());





cout << count << endl;
}


infile.close();

infile.open(name,ios::in);

{
do
{
infile >> y;
if((!infile.eof())||(y=='\n'));
{
count2 ++;
}

if (count2>total2);
{
total2=count2;

}

}while (!infile.eof());





cout << total2;
}


infile.close();

return 0;
}
 

XWRed1

Senior Member
Joined
Oct 31, 2001
in your loop where you count the number of chars, I would think you could just drop an if in there to see if the char is an eol, and if it is, iterate the eol counter.
 

Phase_V

Registered
Joined
Jan 14, 2002
Location
Wisconsin
This will work:

#include<iostream.h>
#include<fstream.h>

char a;
int chars = 0,eols = 0;
char filename[150];
ifstream infile;

int main()
{
cout << "Enter the name of a textfile." << endl;
cin >> filename;
infile.open(filename,ios::in);
infile.unsetf(ios::skipws);

while(!infile.eof())
{
infile >> a;
if(a == '\n')
eols++;
if(a>33 && a < 126)
chars++;
};
chars -= 1;
cout << "Number of Characters: " << chars << endl;
cout << "Number of End Lines: " << eols << endl;
infile.close();
return 0;
}

What you forgot to do was make sure the program didn't skip white spaces. Also the code can be a little cleaner than you had it (as seen above) :)
 
Last edited: