Why can I not print the entire message in this file using C?

Viewed 69
char message[500];
printf("\nEnter your message (Not more than 500 words)\n->");
scanf("%s", message);

FILE *ptr;
ptr = fopen("file.txt", "w");

fprintf(ptr, message);
fclose(ptr);

Here I created an array called message and after receiving the input from the user, I printed the stored string into the file named 'file.txt' but it turns out that only first word of the message array is printing in the file. For example: If I typed 'Hello there, I am learning C' inside the message array and print it to the file, then only 'hello' is being printed on the file. Please explain elaborately.

1 Answers

never use %s in scanf without a maximum field width, or you may very likely overflow your buffer. Using %s is no better than gets.

The issue you are having is simply that %s reads up until the first whitespace. If you want to consume all input, you probably should use fread instead of scanf. That is:

char message[500];
printf("\nEnter your message (Not more than 500 characters)\n->");
size_t s = fread(message, 1, sizeof message - 1, stdin);
message[s] = '\0';

If you want to read only one line of text, you could use fgets. If you want to use scanf to read only one line, you could do: scanf("%499[^\n]", message); (Note that this is significantly different than %499s in that it will not discard leading whitespace, and stops only at the first line break rather than the first whitespace character.) If you want to use scanf to read the entire input stream, you could try something like scanf("%499[^\1]", message); which would probably be adequate for textual input.

Whatever input method you use, make sure you check the return value. If scanf fails to assign an input item (eg, because the input does not match the format string), then reading that item may invoke undefined behavior. If fread returns 0, or (in this case) 499, you will want to add logic to decide what to do.

Related