demo-infile-2d-array - >> goes to whitespace so we get...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
// Programmer: Doug Hogan // Program: Demo Program: 2D Arrays and Input Files // Date: November 6, 2008 // Description: This program reads a matrix from files add multiplies it by // a scalar multiple. #include <iostream> // for cin, cout #include <fstream> // for file input #include <iomanip> // for setw using namespace std; const int NUM_ROWS = 6; // number of rows in matrix const int NUM_COLS = 4; // number of columns in matrix int main() { double scalar; // scalar value by which to multiply double matrix[NUM_ROWS][NUM_COLS]; // input matrix double output[NUM_ROWS][NUM_COLS]; // output matrix (input times scalar) ifstream infile("matrix.txt"); // open file containing matrix if(!infile) // check that file is found { cout << "File not found."; } else // file found, so process it { // INPUT: Read matrix from file for(int row = 0; row < NUM_ROWS; row++) // read in rows { for(int col = 0; col < NUM_COLS; col++) // read in columns { infile >> matrix[row][col]; // read current element
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: // >> goes to whitespace, so we // get just one element at a time } } infile.close(); // close file now since input // from file is done cout << "Enter scalar multiple: "; cin >> scalar; // PROCESS: Multiply by scalar for(int row = 0; row < NUM_ROWS; row++) // go through rows { for(int col = 0; col < NUM_COLS; col++) // go through columns { output[row][col] = scalar * matrix[row][col]; // multiply element-wise } } // OUTPUT: Display product matrix cout << "Product of input matrix and scalar " << scalar << ":" << endl; for(int row = 0; row < NUM_ROWS; row++) // go through rows { for(int col = 0; col < NUM_COLS; col++) // go through columns { cout << output[row][col] << '\t'; // Comment out the above line and uncomment the line below // for a neater output we'll learn about very soon. // (Requires the "iomanip" header above.) //cout << setw(8) << output[row][col]; // print out element // lined up neatly } cout << endl; } } }...
View Full Document

This document was uploaded on 02/10/2011.

Page1 / 2

demo-infile-2d-array - >> goes to whitespace so we get...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online