1 Replies - 815 Views - Last Post: 16 March 2013 - 02:05 PM Rate Topic: -----

#1 Millhouse17   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 16-March 13

Nested for loop, reading file and writing file, help

Posted 16 March 2013 - 01:43 PM

This is my first topic/post/question on dream.in.code so please bear with me.

I am writing a program that will print a table of 0's and 1's
by:

Reading a file, Data.txt, with 2 numbers in it (ex: 5 7).
The first number will represent the number of rows.
The second number will represent the number of columns.

Assuming both numbers are positive and less than 20:
Print a table of 0's and 1's containing the specified rows and column values.
Write the table to a file called Printout.txt.
The table should start with 0's and alternate and use only 2 for loops.

This is what i have so far but my output is
0 1 1 1 1 1 1
0 1 1 1 1 1 1
0 1 1 1 1 1 1
0 1 1 1 1 1 1
0 1 1 1 1 1 1

I cant get the nested for loop correct. I was thinking about using a modulus operator?
Any help would be greatly appreciated.


#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 var1 = 0; var1<rows; var1++)
	{
		cout << "0 ";
		outputFile << var1 << endl;

		for (int var2 = 1; var2<cols; var2++)
		{
			cout << "1 ";
			outputFile << var2 << endl;
		}
			cout << endl;
	}
	system("pause");
	return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Nested for loop, reading file and writing file, help

#2 jimblumberg   User is offline

  • member icon

Reputation: 5669
  • View blog
  • Posts: 17,407
  • Joined: 25-December 09

Re: Nested for loop, reading file and writing file, help

Posted 16 March 2013 - 02:05 PM

Quote

I was thinking about using a modulus operator?

That's a good idea. Give it a try and if you have problems post the new code and qestions.

You also only need one print statement. Not counting the endl print statement.

Jim
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1