C++ issue

mtxblau

Mid Boss
I'm probably looking at this the wrong way, but how does one pass a multiline text file into a multidimension (2 dimension) array?

Basically I'm supposed to take from a separate file (ie file.txt) multiple lines of info; how would I get that into the array?

i.e.,

0 1 2 3 4 5 6 7 8 9

0 a d a m m a r t z

1 j a s o n k i d d

2 j . r o e n i c k

etc.

I'm not sure exactly what I'm doing wrong - any help?
 

antime

Extra Hard Mid Boss
This should probably go into Developers Central, but anyhoo..

Set up a nested loop, one for the rows and one for the columns. So if you have

char foo[m][n]

you do

for (i=0;i < m;i++)

for (j=0;j < n;j++)

fin >> foo[j];

or whatever. That's one way of doing it.
 

Curtis

Member
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
 

antime

Extra Hard Mid Boss
Originally posted by Curtis@April 25 2002,03:24

Oh oh! That is such an inefficient algorithm - a big fat O(n^2) one

No, it's a linear algorithm. There are m*n elements in the array, and you are assigning a value to each of them, once. Granted, it could be more efficient (eg. read in a line at a time), but you'd have to go through every element in the array for each value read or something similar to make it O(n^2) or higher.
 

MasterAkumaMatata

Staff member
<font face="Courier New">#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<MAX_ROW; i++) // initialize array

for (int j=0; j<<span style='color:white'></span>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<rowsUsed; row++){ // display array contents

cout << endl;

for (column=0; column<<span style='color:white'></span>MAX_COLUMN; column++)

cout << myArray[row][column] << " ";

}

cout << endl;

return 0;

}</font>
 
Top