C scanf() to read a string
The scanf()
function in C is used to read input from the user. It allows you to read different types of data, including strings. Here is an explanation of each step involved in using scanf()
to read a string:
Include the necessary header file: To use
scanf()
, you need to include the<stdio.h>
header file in your program. This file contains the declaration of thescanf()
function.Declare a character array to store the string: Before reading the string, you need to declare a character array (also known as a string) to store the input. For example, you can declare an array named
input
with a fixed size of 100 characters:char input[100];
.Use
scanf()
to read the string: To read the string, you can use thescanf()
function with the appropriate format specifier. In this case, you would use the%s
format specifier to read a string. The syntax for usingscanf()
to read a string is as follows:scanf("%s", input);
. The%s
format specifier tellsscanf()
to read a sequence of non-whitespace characters and store them in theinput
array.Process the string: Once the string is read and stored in the
input
array, you can process it as needed in your program.
Here is an example of using scanf()
to read a string:
#include <stdio.h>
int main() {
char input[100];
printf("Enter a string: ");
scanf("%s", input);
printf("You entered: %s\n", input);
return 0;
}
In this example, the program prompts the user to enter a string, reads the string using scanf()
, and then prints the entered string.
Please note that using scanf()
to read strings has some limitations and potential issues, such as buffer overflow if the input string is longer than the size of the character array. It is recommended to use safer alternatives like fgets()
or libraries for more complex input parsing [1]