user3553759
user3553759

Reputation: 1

Read whole digits not split

Hi guys how to read entire digits from file? I mean my input file is 100-4/2 and i wrote this code while(fscanf(in,"%s",s)!=EOF) but it read like this 1 0 0. I want read like 100. How to solve this?

Upvotes: 0

Views: 63

Answers (4)

Mysterious Jack
Mysterious Jack

Reputation: 641

The below is simple program is self explanatory, which reads a file character by character, for each iteration stores this character into a temporary variable temp. and when the value in temp is a numerical character it simply copies this value in array named s.

int main()
{
 char s[10]="\0";//initialzing array to NULL's and assuming array size to be 10
 int i=0,temp=0;
 FILE *fp=fopen("t.txt","r"); //when file has 100-4/2 
     if(fp==NULL)
     {
        printf("\nError opening file.");
        return 1;
     }
     while( (temp=fgetc(fp))!=EOF && i<10 ) //i<10 to not exceed array size.. 
     {
        if(temp>='0' && temp<='9')//if value in temp is a number (simple logic...)
        {
            s[i]=temp;
            i++;
        }   
     }
     printf("%s",s);//outputs 10042
return 0;
}

Upvotes: 0

pmg
pmg

Reputation: 108938

Use "%d" for integers

int value;
if (scanf("%d", &value) != 1) /* error */;
printf("Value read is %d.\n", value);

Upvotes: 0

Vladivarius
Vladivarius

Reputation: 518

It's probably because you are using one-byte character(ANSI) set while the file is written with two-byte characters(Unicode). If you have created the file with the same program that is reading it it's going to read it right, but if not, you can open the file you are reading in notepad, then click save as, and there you can choose ANSI or Unicode.

Upvotes: 1

Rakib
Rakib

Reputation: 7625

You can read the whole line at once using getline() or similar method (also you can read as you are doing if there is only one line, then when EOF is true, whole line is read). Then you can parse the line to extract numbers and operators.

Upvotes: 0

Related Questions