1

I want to read a file into an int array , but I need to do that one element at a time. Here's what's in the file :

    1000320                                                                         
    0110313
    3333000
    2033000
    2203011
    2000010 

And here is the code :

std::ifstream fin("file.in");
for (int i=0; i<6; ++i) //rows
{
    for (int j=0; j<7; ++j) //columns
    {
        fin>>_array[i][j];
    }
}

If I would print _array[0][0] it will output everything that's on the first line. However I want to split what's in the file into rows and columns . What's the most elegant way to do this for an INT array ( I don't want to use a char array although it would be much easier . Also , I know that if I put spaces between the numbers in my file the program would read them one at a time but I want them to be like this )

  • 2
    Unfortunately character by character is really the only way to go. It can be simplified a little by reading line by line into a string, and then get the characters one by one from that string. – Some programmer dude Jan 25 '19 at 22:41
  • @Someprogrammerdude alright , thanks for letting me know and saving me time :) I will declare it as char . – Vlada Misici Jan 25 '19 at 22:45
  • Be careful when reading character by character directly from the file though, as then you have to handle newlines yourself. That's why I recommended reading line by line in the outer loop. – Some programmer dude Jan 25 '19 at 22:54
  • 1
    Just in case `_array` is not a class member, here is some helpful reading: [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier) – user4581301 Jan 25 '19 at 23:44
  • @user4581301 Thanks for pointing that out . I'll be careful about that in the future ! – Vlada Misici Jan 25 '19 at 23:55

2 Answers2

1

You can try using getchar() You'll get char but just convert it to int immediately

char temp = getchar(fin);
_array[i][j] = temp - '0';

Unfortunately there's no getint()

Renziera
  • 81
  • 4
1

in case you want to keep the same structure

#include<fstream>

int main() {
    int n;
    fstream fin("urfile.txt");
    string line;
    int _array[6][7];
        for (int i = 0; i < 6; ++i) //rows
        {
            std::getline(read, fin);
            for (int j = 0; j < 7; ++j) //columns
            {
                _array[i][j] = line[j]-'0';
                cout << _array[i][j];
            }
            cout << '\n';
        }
        fin.close();

}
Spinkoo
  • 2,080
  • 1
  • 7
  • 23