c - Read till end of file into array -


i've been trying figure i'm going wrong can't seem point out error exactly.

i'm trying read text file, these integers

5 2 4 9 10 1 8 13 12 6 3 7 11 

into array a. make sure works, trying print getting large random numbers instead. can me see i'm going wrong please?

int main(){  file* in = fopen("input.txt","r");  int a[100];  while(!feof(in)){     fscanf(in, "%s", &a);     printf("%d", a)   }   fclose(in);  return 0; } 

*this main parts of code related question

for read why using feof wrong, solution similar following. code open filename given first argument program (or read stdin default):

#include <stdio.h>  enum { maxi = 100 };  int main (int argc, char **argv) {      int = 0, a[maxi] = {0};   /* initialize variables */     /* read file specified argument 1 (or stdin, default) */     file *in = argc > 1 ? fopen (argv[1],"r") : stdin;      if (!in) {  /* validate file opened reading */         fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);         return 1;     }      /* read each number file or until array full */     while (i < maxi && fscanf (in, " %d", &a[i]) == 1)         printf (" %d", a[i++]);     putchar ('\n');      if (in != stdin) fclose (in);      printf ("\n '%d' numbers read file.\n\n", i);      return 0; } 

example use/output

using example values in file dat/myints.txt results in following:

$ ./bin/rdints dat/myints.txt  5 2 4 9 10 1 8 13 12 6 3 7 11   '13' numbers read file. 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -