C to read the file and print only numbers

I have a file containing strings as well as numbers. For instance. my Store-1.txt file contains "coffee 2mug -4". I need a c program to store numbers (i.e. 2 and -4), reading a file and storing only numbers in an array.

I can’t figure out exactly how to do this. Any suggestions please.

code

#include <stdio.h> int main(void) { char c,ch; int flag=0; FILE *fptr=fopen("Store-1.txt","r"); if(fptr) { while((c=fgetc(fptr))!=EOF) { if(c=='-' || c== '+') { ch=c; flag=1; } if(c>='0' && c<='9') { if(flag == 1) { printf("%c",ch); flag =0; } printf("%c",c); } } } else printf("Error : file not found"); system("pause"); } 
+4
source share
2 answers

read the file using fgetc() and printf() if

c>='0' && c<='9'

Here is the full working code:

 #include <stdio.h> int main() { char c,ch; int flag=0; FILE *fp=fopen("file.txt","r"); if(fp) { while((c=fgetc(fp))!=EOF) { if(c=='-' || c== '+') { ch=c; flag=1; continue; } if(c>='0' && c<='9') { if(flag == 1) { printf("%c",ch); flag =0; } printf("%c",c); } else flag=0; } } else printf("Error : file not found"); fclose(fp);} 
+4
source
 #include <ctype.h> #include <stdio.h> int main(void) { int ch, n, sign; sign = 1; ch = getchar(); while (ch != EOF) { if (ch == '-') { sign = -1; ch = getchar(); } else if (isdigit(ch)) { n = 0; do { n = n * 10 + ch - '0'; ch = getchar(); } while (isdigit(ch)); n *= sign; /*store n*/ } else { sign = 1; ch = getchar(); } } return 0; } 
0
source

Source: https://habr.com/ru/post/1444534/


All Articles