Home | Forums | What's new | Resources | |
C++ issue |
mtxblau - Apr 24, 2002 |
Curtis | Apr 24, 2002 | |||
Oh oh! That is such an inefficient algorithm - a big fat O(n^2) one
Sorry...I've just been learning about this at Uni |
mtxblau | Apr 24, 2002 | |||
Oh, I didn't think there'd be a reply. |
MasterAkumaMatata | Apr 26, 2002 | |||
#include <iostream.h> #include <fstream.h> #include <stdlib.h> const int MAX_ROW=10; // specify array row size here const int MAX_COLUMN=10; // specify array column size here int main(){ char myArray[MAX_ROW][MAX_COLUMN]; // declare 2D array of char elements int row=0, column=0, rowsUsed=0; // initialize array counters bool arrayIsFull=false; // initialize flag to quit while loop below ifstream dataFile("file.txt"); // initialize hard-coded input filestream for (int i=0; i for (int j=0; j<MAX_COLUMN; j++) myArray[j]='\0'; if (dataFile.fail()){ // error opening file or file not found cerr << "Error opening file or file not found.\n"; exit(1); // exits main } while ((dataFile >> myArray[row][column]) && // while you can keep reading (!arrayIsFull)){ // and array is not full column++; // go to the next column of array if (column>=MAX_COLUMN){ // end of column reached column=0; // restart over at first column row++; rowsUsed++; // go to the next row of array if (row>=MAX_ROW){ // check for array out of bound error cerr << "\nArray is full... will not read further.\n"; arrayIsFull=true; // quit the while loop b/c array is full } } } dataFile.close(); // close file after use for (row=0; row cout << endl; for (column=0; column<MAX_COLUMN; column++) cout << myArray[row][column] << " "; } cout << endl; return 0; } |