Error while reading character using gets function

178 views Asked by At

I am writing a string to a file. But only the first part of the string is only inserted to file. Others are missing. For eg: If I write "I Like Flowers", "I" is only written into file.

    #include <stdio.h>
int main()
{
        char string[50];
        int marks,i,n;
        FILE *fptr; fptr=(fopen("string.txt","w"));
        if(fptr==NULL){
                printf("Error!");
                return 0;
        }
        printf("Enter a string : \n");
        scanf("%s", string);
        //fprintf(fptr,"%s",string);
        fwrite(string, 1, sizeof(string), fptr);

        fclose(fptr);
        return 0;
}
2

There are 2 answers

6
hmjd On BEST ANSWER

The scanf() will stop reading at the first space: that is the problem. The scanf("%s") only reads the I from standard input. To read the entire line use fgets() instead. Use strlen() to write only what was read instead of using sizeof(string).

0
Bandi Ravi Teja Naidu On

In your code scanf("%s",string) only takes the string up to the first space. To read the total string "I Like Flowers", you have to use the scanf function like this:

scanf("%[^\n]s,string);

it will work.