something wrong with my fscanf?

This is a discussion on something wrong with my fscanf? within the C Programming forums, part of the General Programming Boards category; Hi. I'm trying to place the contents of a text file with integers into an array. But the wrong values ...

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    15

    something wrong with my fscanf?

    Hi. I'm trying to place the contents of a text file with integers into an array.
    But the wrong values are being output to the screen:
    Code:
       FILE *fin;
       char file_name_in[20]= "test.txt";
       int int_array[1000],c;
    
       /* test to see if file opens */
       fin = fopen(file_name_in, "r");
       if (fin == NULL){
          (void)fprintf(stderr,"Cannot open input file %s\n",file_name_in);
       }
    
       int i=0;
       while((getc(fin))!=EOF){
          fscanf(fin, "%d",&c);
          int_array[i]= c;
          i++;
       }
       for (i=0;i<=7;i++){
          printf("%d",int_array[1]);
       }
    any ideas?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,697
    Code:
     while((getc(fin))!=EOF)
    This will get one character from your file. Do you have an extra character in you file that you want to dispose of? You probably want something like:
    Code:
     while((fscanf(fin, "%d",&c)  )!=EOF)
    Jim

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    while ( i < 1000 && fscanf(fin, "%d",&c) == 1 )
    would be an improvement.

    At least it won't smash the array with a large file, or lock up if the file contains junk.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Code:
       for ( i=0; i <= 7; i++ ){
          printf("%d",int_array[1]);
    Look closely... what's wrong with this picture?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fscanf fails?
    By erjoalgo in forum C Programming
    Replies: 13
    Last Post: 04-05-2010, 05:48 AM
  2. segfault in fscanf and struct question
    By AstralZecha in forum C Programming
    Replies: 15
    Last Post: 03-28-2010, 08:58 AM
  3. Replies: 9
    Last Post: 07-15-2004, 03:30 PM
  4. God
    By datainjector in forum A Brief History of Cprogramming.com
    Replies: 746
    Last Post: 12-22-2002, 11:01 AM
  5. fscanf on sun's
    By brif in forum C Programming
    Replies: 2
    Last Post: 04-14-2002, 01:22 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21