C Programming: String Input Methods Guide
In the C language, there are several ways to input strings.
- You can use the scanf() function to read strings from the standard input stream, for example:
char str[100];
scanf("%s", str);
- You can use the fgets() function to read a line of string from the standard input stream, for example:
char str[100];
fgets(str, 100, stdin);
- Using the gets() function: It is not recommended to use the gets() function, but it can also be used to read a line of string from the standard input stream.
char str[100];
gets(str);
- You can use the getchar() function to read input character by character until a newline is encountered.
char str[100];
int i = 0;
char c;
while ((c = getchar()) != '\n') {
str[i++] = c;
}
str[i] = '\0';
When using the gets() function, be mindful that the length of the input string should not exceed the size of the array, as it may result in a buffer overflow. The fgets() function is more secure and is recommended for use.