Reading from txt file and putting into array

I am trying to read some data from txt file and put it into char array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char letter[8][11];
char c;
ifstream infile("waldorf.txt");
if(infile.is_open()){
   while(!infile.eof()){
        for(int i=0; i<8; i++){
          for(int j=0; j<11; j++){ 
              infile.get(c);
              letter[i][j]=c;
               break;
                 }
               break;
               }
               }
              }


can anyone show me my mistake, waldorf.txt is as follow:
abcDEFGhigg
hEbkWalDork
FtyAwaldORm
FtsimrLqsrc
byoArBeDeyv
Klcbqwikomk
strEBGadhrb
yUiqlxcnBjf
Last edited on
Why do you need a 2d array?
Alright theres a pretty simple way to do this that will save you a bunch of time.

There is no real need for a while loop here if you just set your for loops like you are.

1
2
3
4
5
6
7
8
9
10
11

for(int i = 0; i<ROWS; i++)
{
     for(int j = 0; j<COLS; j++)
        {
        infile>>letter[i][j]; //This is a simple way of getting one letter at a time
        
        cout<<letter[i][j]; //Way to check your work
        {
cout<<endl;
}


The reason you don't need the while loop is because you have already determined how big your 2d array will be, so you can set your for loop parameters accordingly.

The reason I don't use the .get option has to do with if you can make a program more simple why not do it. The >> option is just what I know best but I am sure you can make the .get option work just as well, seemed saving it to the char c had something to do with it just didn't have time to look up why.

If the teacher tells you make a 2d array 800x10000 then using the !infile.eof would be a good idea because he might only give you 300 of those rows and you will have empty spaces on your printout if you do have to print it out.

So it would look like

John
Goes
To
School
.
.
.
.
.
.
.
.

With the periods representing empty lines what have you.

I would recommend looking up arrays and getting to know them very well as I know my teacher in about all of his problems he will make us do something with an array. The resources on this site are very good to start with.

This little piece of code should get you on the right track.

Hope I could help.
Thanks very much popasquat; but there is another rpoblem:
what do I need to do if I just know that waldorf.txt consists of m COLUMNS and n ROWS, and I do not know the content of waldforf.txt;with Columns I can do the following:
1
2
3
4
char letters[m][n];
string line;
if(infile.is_open()) getline(infile, line);
n=line.size();
Topic archived. No new replies allowed.