getting string input in c
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%49s", name);
printf("Hello, %s!\n", name);
return 0;
}
Explanation:
1. #include <stdio.h>
: Includes the standard input-output library in the program.
int main() { }
: Defines the main function where the program execution starts.char name[50];
: Declares a character array namedname
capable of holding up to 49 characters (plus the null terminator\0
) for storing the input string.printf("Enter your name: ");
: Displays the message prompting the user to enter their name.scanf("%49s", name);
: Reads the input from the user usingscanf
.%49s
reads a string input, ensuring that only up to 49 characters are stored in thename
array to prevent buffer overflow.printf("Hello, %s!\n", name);
: Prints the greeting message with the name entered by the user using the%s
format specifier.return 0;
: Indicates the successful termination of themain
function and the program.