Which of the following function is more appropriate for reading in a multi-word string in c?
Question
Which of the following function is more appropriate for reading in a multi-word string in c?
Solution
The most appropriate function for reading in a multi-word string in C is fgets().
Here's why:
-
scanf()stops reading input as soon as it encounters a space, so it's not suitable for multi-word strings. -
gets()can read multi-word strings, but it's dangerous because it doesn't check the size of the input and the size of the buffer. This can cause buffer overflow, which can lead to crashes or security vulnerabilities. -
fgets()is the best choice because it reads in a multi-word string and also checks the size of the buffer to prevent overflow. It reads until a newline character, an end-of-file, or a specified limit.
Here's an example of how to use fgets():
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin); // Reads in a line from stdin and stores it into str
printf("You entered: %s", str);
This code will read a line of input (up to 99 characters, because one character is reserved for the null terminator) and then print it out.
Similar Questions
Which of the following function is more appropriate for reading in a multi-word string?
function is more appropriate for reading in a multi-word string?ans.
Which of the following function is more appropriate for reading in a multi-word string? ans. scanf() printf() gets() puts()
Which of the following function is more appropriate for reading in a multi-word string?ans.puts()scanf()gets()printf() Previous Marked for Review Next
How many keywords are there in c ?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.