C++ File handling help needed

The following program is actually written to count the number of alphabet in a .txt file. But the problem is that it gives different outputs every time. What am I doing wrong here?



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
 #include<iostream>

    #include<fstream>

    #include<conio>

    #include<dos>


    char alph[100];

    int cont=0;

    void count()

    {

    for(int i=1;i!='\0';i++)
	{
		if(alph[i]!='\0')
		{

			cont++;
			cout<<"Count="<<cont<<endl;
			delay(10);
	}        
    }


    cout<<cont;


    }


    void main ()

    {
	
    ofstream fout;

	fout.open("File.txt");

	fout<<"Stud"<<endl;

	fout<<"Typo"<<endl;

	fout<<"Not impressed"<<endl;

	fout.close();


	ifstream fin;

	fin.open("File.txt");

	count();

	fin.close()

	getch();
    
Last edited on
Where do you actually read from fin?

alph[] is an uninitialized array. What do you think it contains? hint: garbage.

main should return type int.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

- int main(), not void main()
- conio is not a standard header file, to be avoided
- if(alph[i]!='\0') is not sufficient check for alphabet, it'll pick up numbers, punctuation, etc
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
#include <iostream>
#include <fstream>
#include <cctype>

int main ()
{
    std::ofstream fout("D:\\output.txt");
    fout << "Stud \n";
    fout << "Typo \n";
    fout << "Not impressed \n";
    fout << "Hello \n";

    fout.close();

    std::ifstream fin("D:\\output.txt");
    char ch;
    int counter{};
    while (fin >> ch )
    {
        if(isalpha(ch))
       {
           counter ++;
       }
    }
    std::cout << counter << '\n';
}
@gunnerfunner

But the output comes to
 0
Last edited on
Not on my side, 25
@gunnerfunner

The code was run on the website cpp.sh


It show
0

Last edited on
Try running it locally on your laptop off an IDE or command line, cpp.sh can't write to files. I'm getting 0 off cpp.sh as well
You might also try Coliru
(This is @gunnerfunner's solution) :)
http://coliru.stacked-crooked.com/a/904b6ab8813bd415
Topic archived. No new replies allowed.