for loop not storing a value for position 0

I am having an issue with my last for loop in my program. It is not storing any value for position 0 and it's printing out the null values. Here is my program.

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
#include <iostream>
#include <string>
#include <fstream>
#include <ctype.h>

using namespace std;

int main() {

	ofstream myfile("string.dat");

	string str1;

	cout << "Please enter a sentence : ";
	getline(cin, str1);
	if (myfile.is_open())
	{
		myfile << str1;
		myfile.close();
	}
	else cout << "Unable to open file";
	
	cout << endl;
	cout << endl;
	cout << endl;
	int const size = 1000;
	char alpha[size]; // declaring the array
	int i=0;
	ifstream file("string.dat");
		if (file.is_open())
		{
			while (file.getline(alpha, size)) // telling the program where to get the string from the file
			{
				while (alpha[i] != '\0') { // populating and printing out the array up until the null values
					alpha[i] = toupper(alpha[i]);
					cout << alpha[i];
					i++;
				}
				
			}
			file.close();
		}

		else cout << "Unable to open file";
		cout << endl;
		cout << endl;
		for (int i = 0; i < size; i++) {
			if (alpha[i] != '\0') {
				cout << alpha[i];
			}
			
		}

	
		 

	return 0;
}
Last edited on
There is a lack of symmetry in the file handling. At line 18 a single string is written to the file which is then closed.

At line 32, rather than reading a single line from the file, there is a while loop. The first iteration proceeds ok. Then the second time, the getline fails to read anything, it writes a null byte to alpha[0]. Then at line 47 the entire array alpha is processed, any non-zero character is output.



@Chervil

Thank you so much! With that little change I was able to print out the loop!
Topic archived. No new replies allowed.