Please explain simple while loop formatting error.

Someone please tell me why the loop here doesn't read the .txt file properly, but when I manually type it out in 81 lines of code, it does. I'll post the code with the loop first, then the one with manual entry second. The first code reads 2 spaces first, then cuts off the last 2 characters in the file. The second code works properly, reading and displaying all 81 characters that are contained in the .txt file.

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

using namespace std;

int main()

{
	const int RANGE=81;
	int inc,counter;
	char number[RANGE];
		
	ifstream sudoku ("sudoku.txt");
	
	if (!sudoku)
	{
		cout<<"No such file."<<endl;
		return -1;
	}
	
	while (!sudoku.eof())
	{
		sudoku.get(number[counter++]);
	}

	counter=0;
	
	while (inc<RANGE)
	{
		cout<<number[counter++];
		inc++;
	}
	
	
	
	return 0;
}


And now the second one.

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

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()

{
	const int RANGE=81;
	int inc,counter;
	char number[RANGE];
		
	ifstream sudoku ("sudoku.txt");
	
	if (!sudoku)
	{
		cout<<"No such file."<<endl;
		return -1;
	}
	
	while (!sudoku.eof())
	{
		sudoku.get(number[counter++]);
	}

	counter=0;
	
	cout<<number[counter++];
	cout<<number[counter++];
	cout<<number[counter++];
	cout<<number[counter++];
	cout<<number[counter++];
	cout<<number[counter++];
	
        // I'd just put this line in 81 times and it would display correctly.
	
	return 0;
}
Last edited on
You don't initialise inc so its value at start of the loop is unknown.

It is probably greater than 81 so the loop doesn't start.

You also do not initialise counter before reading the text file so I think it is only luck that the reading loop works.

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

using namespace std;

int main()

{
	const int RANGE=81;
	int inc=0,counter=0; ///// changes
	char number[RANGE];
		
	ifstream sudoku ("sudoku.txt");
	
	if (!sudoku)
	{
		cout<<"No such file."<<endl;
		return -1;
	}
	
	while (!sudoku.eof())
	{
		sudoku.get(number[counter++]);
	}

	counter=0;
	
	while (inc<RANGE)
	{
		cout<<number[counter++];
		inc++;
	}
	
	
	
	return 0;
}

Last edited on
Thanks so much. That fixed it. I'm new to c++ so forgive my ignorance. I thought if it wasn't declared, it started at 0.
Topic archived. No new replies allowed.