Hi,

I'm trying to create a 2d array that will fill itself up with numbers i have in a text file.

My text file looks like this:

1 5 4
2 6 3
3 9 4
4 1 8
5 2 2

So, I want to create an array with 5 rows and 3 columns that will print this exact output to the screen.

Could anybody help me with the code please?

Thank you :)

Recommended Answers

All 18 Replies

>> Could anybody help me with the code please?
Not unless you show some work.
But it's not that hard. There are two problems to overcome -- 1) filling the array 2) reading values from a file. Once you have those two done there's really no problem. Show attempts on both.

#include <iostream.h>
#include <fstream.h>

int main()
{
/* open the file to read from in this case being your text file*/
char chars[50];
char newline = '\n'; // for the get line function's 3rd argument .. acts as a terminating delimeter.

ifstream in("c:\\documents and settings\\your profile name\\desktop\\theNameOftheTXTfile.txt");

while(! in.eof())
{
in.getline(chars,50,newline);
cout<<chars<< endl;
};
system("pause"); // I use DEV as im a hobby 
                         //programmer.
return 0;
};

I didnt compile this code.. should work, if not post the error, and I will get back to this post later.

NOTE: This reads the text in as characters, so although they are numbers in the note pad, they will be read in as characters. **some people like to write stuff to text files, and read from text files without having to use the isstream class if your doing most of your work on a windows platform.

commented: Bad Cody, bad Cody. -2

Cody: if you want to post code, that is ok, but please

  • Use code tags [code=c++] /* code goes here */ [/code]
  • Don't use ancient header files with .h extension
  • Don't use eof() as you did in line 12 because it doesn't work like that

>> This reads the text in as characters
Why? it could read into integer variables just as easy. By reading in as strings the strings have to be converted into ints before they can be used. That just extra unnecessary work.

Ok, sorry for not showing you what i've got.

I'm looking for something really simple, all I want to do is fill an array/matrix with my infile!!

In my example, there were only a few rows of information, but this needs to be able to be replaced with something, say, of 100 row of information. Thus, the program needs to be quite general.

I thought maybe zero the array first?

At the moment I have this code for the array...

k = 0;

  for (i=1; i<101; i++)
  
  {
    
  for (j=1; j<3; j++)
  {  
     matrix[i][0] = i;
     matrix[i][1] = k;
     matrix[i][2] = k; }

  printf("%d", matrix[i][0]);
  printf("\t%d", matrix[i][1],k);
  printf("\t%d", matrix[i][2],k);
  printf("\n");}

}

And as for uploading the input file from notepad, i believe i should use...

inFile.open("input.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }

Am I on the right tracks? Oh, and that code already posted din't work at all :S

You don't need to zero out the array. You already know the size (5 x 3), so declare it that size:

int matrix[5][3];

i would just read it in like this:

for (int i = 0; i < 5; i++)
{
    for (j = 0; j < 3; j++)
    {
        inFile >> matrix[i][j];
        // display matrix[i][j]
    }
}
Member Avatar for iamthwee

You don't need to zero out the array. You already know the size (5 x 3), so declare it that size:

Nope...

In my example, there were only a few rows of information, but this needs to be able to be replaced with something, say, of 100 row of information. Thus, the program needs to be quite general.

Yeah, sadly it needs to be replaced with a file of unknown size :(

I've been told it won't be over 100 rows though :)

Missed that part of the problem. Thanks.

So here is the basic program I have. All this does is read a .txt file and produce a 100x3 array that is zero'd. What alterations/additions do I make to the code to import the .txt file into the array? Thanks in advance!!

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

int k,i,j;
int matrix[101][5];

main () {
  
  ifstream inFile;
  inFile.open("input.txt");
  
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }
  inFile.close();
    
  k = 0;

  for (i=1; i<101; i++)
  
  {
    
  for (j=1; j<3; j++)
  {  
     matrix[i][0] = k;
     matrix[i][1] = k;
     matrix[i][2] = k; }

  printf("%d", matrix[i][0]);
  printf("\t%d", matrix[i][1],k);
  printf("\t%d", matrix[i][2],k);
  printf("\n");}

}

you don't need lines 25-29 to zero out the array. Do it when the array is declared, like this: int matrix[101][5] = {0}; >>What alterations/additions do I make to the code to import the .txt file into the array?
Code that reads the text file. Start by deleting lines 1 to 3 -- al those files are obsolete in C++. Most likely all you need is this:

#include <iostream>
#include <fstream>
using namespace std;

Next declare an ifstream object Then in a loop read the integers into the array. See Vernan's post #6 above, which is an example of how to read the file.

Sadly, the c++ compiler i have to use at uni must use those headers, as it isn't a very new program. So I do have to use them :(

You say to declare an ifstream object and then in a loop, read the integers into an array.

I know this is what I must do, but this is the code I am struggling with... I've never come across any examples of this before. Could you possibly give me some brief code that will read the integers into the array?

Thanks for the help with zeroing, that worked a treat :)

So you do know that you have three columns? You don't know how many rows, but there are three columns? If you don't know how many columns, this won't work. If it's different from 3, change numCols. Anyway, here's a way to read it in:

int numCols = 3;
int numRows = 0;


while (inFile >> matrix[numRows][0])
{
      printf ("%d\t", matrix[numRows][0]);
      for (j = 1; j < numCols; j++)
      {
          inFile >> matrix[numRows][j];
          printf ("%d\t", matrix[numRows][j]);
      }
      numRows++;
      printf ("\n");
}

inFile.close ();

You have

inFile.close ();

at the top before anything is read in, so you want to take that out. I think these lines are going to give you an error:

printf("\t%d", matrix[i][1],k);
printf("\t%d", matrix[i][2],k);

You only have one "%d", but you have two parameters. I'd take the "k" parameter out.

That works perfectly, thank you so much!!

Ok, for my next question:

I want there to be three columns for the text file yes. HOWEVER, i want to have 2 further columns with empty data in them, ready to put calculations in. Is this possible?

Sadly, the c++ compiler i have to use at uni must use those headers, as it isn't a very new program. So I do have to use them :(

Oh, that's unfortunate that your school is making you learn something that will never be used in the real world. We tossed out those compilers 15 years ago.

I've never come across any examples of this before.

Well, then you didn't read the POST #6 very well, if at all, because it has exactly what you need.

Dunno what I was thinking at the time.. please forgive me.

Dunno what I was thinking at the time.. please forgive me.
'

Nothing like a two-year late response :)

int a [3][3]; //can be modify..in this example..3x3 = 9..
fstream open("bottles.txt");

for ( int i=0;i<3 ;i++) {
    for (int j=0;j<3 ;j++){
	open >> a[i][j];
	}
}	
for ( int i=0;i<3 ;i++) {
    for (int j=0;j<3 ;j++){
		cout<<a [i][j]<<" "<<endl;
	}
}

Hello

For : VernonDozier

printf it's used in C language not in C++, in C++ it's used : 'cout'.

commented: Not necessary -1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.