Reading intergers from a text file in c -
i want take input file c program. input should consists of numbers , characters thereafter want differentiate both of them. fscanf returns 0 when encounters non integers, not worthy of being used here, 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 @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; }
Comments
Post a Comment