简体   繁体   中英

How to get separeated ints from file in C

How can I get, in C, a separated int's from a file like "1, 2,,3,,, 5,6" (to an array or one by one) without getting the garbage like " " or ","?( ,,, is a possible case) I thought about strtok but it's only deals with strings, and I don't know what will be the length of the file, so maybe fgets isn't the solution.. I tried this:

   fp=fopen("temp.txt","r");
   if(fp==NULL)
   {
        fprintf(stderr,"%s","Error");
        exit(0);
   }
   while(fscanf(fp,"%d",&num)!=EOF)
   {
      printf("first num is %d",&num);
   }

But I think it will be a problem because of the unknown file size and because of the garbage problem. What do you think?

thanks!!

Use scanf() 's return value

int chk;
do {
    chk = fscanf(fp, "%d", &num);
    switch (chk) {
        default: /* EOF */;
                 break;
        case 0: fgetc(fp); /* ignore 1 character and retry */
                break;
        case 1: printf("num is %d\n", num);
                break;
    }
} while (chk >= 0);

The program below works for any format of the file and which can extract any integral number contained there

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
#include <ctype.h> 


int main(int argc, char *argv[])
{
    FILE* f=fopen("file","rb");
    /* open the file  */
    char *str=malloc(sizeof(char)*100);
    /* str will store every line of the  file */
    if (f!=NULL)
    {
        printf("All the numbers found in the file !\n");
        while (fgets(str,100,f)!=NULL)
        {
            int i=0,n=0;
            /* the n will contain each number of the f ile  */
            for (i=0;i<strlen(str);i++)
            {
                int test=0;
                /* test will tell us if a number was found or  not  */
                while (isdigit(str[i]) && i<strlen(str))
                {
                    test=1;
                    n=n*10+str[i]-'0';
                    i++;
                }
                if(test!=0)
                    printf("%d\n",n);
                /* print the number if it is found */
            }
        }


        fclose(f);
    }
    free(str);
    //free the space allocated once we finished
    return 0;
}

if our file is

Hell0a, How12
ARe 1You ?
I live in 245 street

it will generate

All the numbers found in the file !
0
12
1
245

Hope it helps !

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