-2

I asked the user for a file with an array and I copy the array from the file to the c[50] array, also printing out each value as I add the values to the array. Out of curiosity I decided to reprint the values off of the c[50] array and to my surprise there were totally different numbers (BIG numbers).

#include <iostream> 
#include <stdio.h>
using namespace std;

int main() {
  int c[50], k = 0, d[50], i, s;
  float r;
  FILE * fin;
  char filename[15], l;
  printf("De el nombre del archivo:\n\n");
  scanf("%s", filename);
  fin = fopen(filename, "r");
  if (fin == NULL) {
    printf("\nNo se pudo abrir el archivo.\n");
    return 1;
  }
  fscanf(fin, "%c", & c[k]);
  while (!feof(fin)) {
    printf("%c", c[k]);
    k++;
    fscanf(fin, "%c", & c[k]);
  }
  //s is the size of the array idk why it makes the k double the amount that what it really is but it doubles it.
  s = k / 2;
  printf("%d\n", s);

  for (i = 0; i < s; i++) {
    printf("%d  ", c[i]);
  }

  return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 7
    If this is tagged with [tag:c] why is there C++ namespace declaration in the code? – t0mm13b Jun 10 '17 at 00:44
  • `fscanf(fin, "%c",&c[k]);` --> `fscanf(fin, "%d",&c[k]);` or `int c[50]` --> `char c[50]` – BLUEPIXY Jun 10 '17 at 00:46
  • thanks you guys work fast – Daniel De Jesús Jun 10 '17 at 00:49
  • Note [`while (!feof(fp))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong), though remarkably, your code is sub-optimal but close to correct because you do an input operation before detecting EOF with `feof()`. It's better to check the return value from `fscanf()` directly, though. You can avoid repetition of the call that way: `while (fscanf(fin, "%d", &c[k]) == 1) { … }`. Printing data after you've read it is good practice; printing while you read it may not show bugs. – Jonathan Leffler Jun 10 '17 at 01:26

1 Answers1

1

The completely random numbers your seeing is because you are reading a character (1 byte) fscanf(fin, "%c", & c[k]); into an integer (4 bytes) int c[50]; thus only the lowest byte is being written. You should have seen warnings when compiled like this:warning: format '%c' expects argument of type 'char*', but argument 3 has type 'int*' [-Wformat=]. Then when you print the value the first time printf("%c", c[k]); each character from the file is printed recreating the file contents.

When I changed the first printf("%c", c[k]); to printf("%d\n", c[k]); the program outputted the same numbers each time it was printed.

Use the proper input specifier for the data being inputted.

Grifplex
  • 192
  • 1
  • 12