简体   繁体   中英

Reading intergers from a text file in c

I want to take input from a file to my c program. The input should consists of Numbers and characters thereafter i want to differentiate both of them. As fscanf returns 0 when it encounters a non integers, it not worthy of being used here, what to do?

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

int main(){
    int num, status;
    FILE *fp = fopen("data.txt", "r");
    while(EOF!=(status = fscanf(fp, "%d", &num))){
        if(status == 1){
            printf("%d\n", num);
        } else { //if(status == 0){
            (void)fgetc(fp);//replace by @chux's suggestion

int ch; while(EOF!=(ch=fgetc(fp)) && ch != '-' && !isdigit(ch)); if(ch == '-'){ int pch = fgetc(fp); if(isdigit(pch)){ ungetc(pch, fp); ungetc(ch, fp); } } else { ungetc(ch, fp); }

        }
    }
    fclose(fp);
    return 0;
}

simply just read the file one by one character at a time and check the range of the value as we know the value in integer value of '0' to '9' is from 48 to 57, just check and use. Hope it will helps you.

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