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)
.
Error while reading character using gets function
문제
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;
}
해결책
다른 팁
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.
제휴하지 않습니다 StackOverflow