C program to read a file and print just the numbers
c
Solution
read a file using `fgetc()` and `printf()` it 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);}
Problem
I have a file containing strings as well as numbers. Eg. my file Store-1.txt contains "coffee 2mug -4". I need a c program to store the numbers only (i.e 2 and -4) by reading a file and saving just the numbers into an array. i am not able to figure out how exactly to do this. Any suggestions please. code is ``` #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"); } ```