Nested For loop

I am attempting to read a file with 2 numbers in it. The first indicates the number of rows the second, the number of columns.

So for a file (Data.txt) that contains the numbers 5 7, I want to display

0 0 0 0 0 0 0
1 1 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 1 1
0 0 0 0 0 0 0

and write that output to a file.

I can display the correct number of rows and columns but I can't figure out how to display alternating rows of 0's and 1's.

Any help would be greatly appreciated.


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

using namespace std;

int main()
{
	ifstream inFile;		//declare file

	// declarations
	int rows;
	int cols;

	inFile.open("Data.txt");	//open file

	inFile >> rows;
	inFile >> cols;

	inFile.close();			//close file

	ofstream outputFile;
	outputFile.open("Printout.txt");

	for (int x = 0; x<rows; x++)
	{
		for (int y = 0; y<cols; y++)
		{
			cout << "X ";
		}
		cout << endl;
	}

	outputFile.close();

	system("pause");
	return 0;
}
closed account (Dy7SLyTq)
in the nested for cout<< the counter % 2
change cout<<'X'; to cout<<y%2; which is what DTScode said to do ... I think.
BTW X is not a string so you shouldn't use "X" but 'X'.. also 'X' is not a counter for the first loop ... it is 'x'.
closed account (Dy7SLyTq)
yes that is what i meant. but first of all he did "X " which is a string and technically "X" is a string of one character and 'X' is a character
Yes... I wasn't aware that that C++ allows a one character string ending with '\0' which is itself a character. However your solution to the above was nicely said and done...it remains to be seen if it bears fruit.
Thanks. Changed the row counter to display the modulus division and its working great now!

1
2
3
4
5
6
7
8
9
10
for (int x = 0; x<rows; x++)
	{
		for (int y = 0; y<cols; y++)
		{
			cout << (x % 2) << " " ;
			outFile << (x % 2) << " ";
		}
		outFile << endl;
		cout << endl;
	}
Topic archived. No new replies allowed.