Counting characters in a textfile

Hi guys!

A program I am writing needs to be able to count how many characters are in a file. I have managed to get it to count the amount of lines, however I am having no joy getting it to count characters correctly. Could somebody give me some pointers on how to do this.

Thanks :)
This is the code I have so far, program returns amount of lines correctly, however amount of chars always remains at 0. Here is my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <iomanip> 
using namespace std;

int main()
{
string file1,file2, line, ch, tag, word, comment;
ifstream ipfile;
ofstream opfile;
char c; 

int amountline = 0;
int amountcha = 0;
int amounttag = 0;
int amountcomment = 0;
int amountword = 0;
cout <<  " Please enter the name of the file you wish to check" << endl ;
cin >> file1;


ipfile.open(file1.c_str());


while ( getline(ipfile,line ) ) 

{

	amountline ++;



}



while (!ipfile.eof())


	{

		amountcha ++;

	}




cout << " This file contains :" << amountline << " lines" << endl;
		cout << " This file contains :" << amountcha << " charecters" << endl;






return 0;
}




Its probably something really simple... that I am just not understanding.

Thanks
For you while loop use this:
1
2
3
4
5
6
7
8
9
10
11
int number_of_chars = 0;
char c;

while(true)
{
	if(in.peek() == -1)
		break;
	c = in.get();
	if(c != '\n') 
		++number_of_chars;
}


And then print out the number
Last edited on
Since in ASCII text 1 character is 1 byte, you can use seekg and tellg to get the number of characters
Thanks guys got it working :). x
Topic archived. No new replies allowed.