While Loop only run once

Hi everyone, I've been taking an intro course to programming. I'm stuck on this problem. The program is supposed to print out whatever from the local file and print it out on the screen and make a copy to another file.
Here's my code. Could you point out where did i go wrong ?
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
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
	char fn[50], fno[50], ch;
	cout << "Enter a file name: " << endl;
	cin >> fn;
	int vowels = 0;
	int lines = 1;
	int consonants = 0;
	int digits = 0;

	ifstream infile(fn);

	if (infile) // check if this is a good file
	{
		cout << "Enter a name for output file" << endl;
		cin >> fno;
		

		while (infile.get(ch)) //read the file
		{
			if (ch == 'a' || ch == 'o' || ch == 'e' || ch == 'i' || ch == 'u' || ch == 'A' || ch == 'O' || ch == 'E' || ch == 'I' || ch == 'U')
			{
				vowels++;
			}
			else if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')
			{
				consonants++;
			}
			else if (ch == '\n')
			{
				lines++;
			}
			else if (ch >= '0' && ch <= '9')
			{
				digits++;
			}
			cout << ch;
			infile.close();
			ofstream outfile(fno);
			{
				outfile << ch;
			}
			outfile.close();
		}
	}
	//output to screen
	cout << endl;
	cout << "Vowels: " << vowels << endl;
	cout << "Lines: " << lines << endl;
	cout << "Consonants: " << consonants << endl;
	cout << "Digits: " << digits << endl;

}


You are closing your input file after reading only one character. Line 44.

You should close the file AFTER your while loop, after the closing bracket on line 50.

You should not open and close your output file in the while loop. Open it before the while loop and close it after the while loop.
oh wow. Thank you very much. :D
There are functions in the C library header <cctype> that could be beneficial for testing if the character is a digit or alphabetic, as well as reducing the number of checks needed for upper/lower case.

http://www.cplusplus.com/reference/cctype/
This can bite you if your file was made on a different OS than your program.
the result in a text file for \n is different bytes across different OS. It won't matter for homework, but watch out for this.

else if (ch == '\n')


Last edited on
My understanding is the C++ runtime correctly deals with whatever line ending your platform is, as long as the file isn't being opened in binary, so doing == '\n' should be safe.
Topic archived. No new replies allowed.