简体   繁体   中英

Reading file of 1's and 0's one at a time

In C++ I am trying to read from the following file into an array:

0000000000
0000000000
0000000000
0001110000
0001010000
0001110000
0000000000
0000000000
0000000000
0000000000

I am using the following to put each int into an array:

  X = (int* )malloc(n*n*sizeof(int));
  for (int i = 0; i<(n*n); i++){
    j = read.get();
    if (isdigit(j)){
        *(X+i) = j - '0';
    }
  }

But when I output to array to a file I get the following output:

0000000000
0000000000
0000000000
0000001110
0000000101
0000000011
1000000000
0000000000
0000000000
0000000000

And I don't believe there is anything wrong with how I am outputting my array:

for (int i = 0; i<(n*n); i++){
      write << *(X+i);
      if (((1+i) % n) == 0){
        write << endl;
      }
}

I tried reading with the following but it didn't seem to work:

for (int i = 0; i<(n*n); i++)
        {
            read >> *(X+i);
        }

The problem is that you're incrementing i even when isdigit(j) is false. So you're leaving the array elements corresponding to the newlines in the file uninitialized, and also not reading all the digits because you're counting the newlines. You need to put the increment inside the if .

for (int i = 0; i < n*n; ) {
    char j = read.get();
    if (isdigit(j)) {
        X[i++] = j - '0';
    }
}

BTW, if you're using a pointer as an array, use array syntax X[index] rather than *(X+index) . It makes the intent clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM