How to read characters from a string in C language?
In the C language, it is common to use loops and array indexes to read each character of a string one by one.
#include <stdio.h>
int main() {
char str[100];
int i;
printf("请输入一个字符串:");
gets(str);
printf("输入的字符串是:%s\n", str);
printf("字符串的字符依次为:\n");
for(i = 0; str[i] != '\0'; i++) {
printf("%c\n", str[i]);
}
return 0;
}
In the code above, we first declare a character array named ‘str’ to store the input string. Then we use the gets() function to read the string from standard input. Next, we use a for loop to iterate through each character in the string until we encounter the string termination character ‘\0’. Within the loop, we use the printf() function to print out each character one by one.
It is important to note that the above code uses gets() function to receive string inputs. However, gets() function has security issues, so it is recommended to use a safer alternative like fgets() function in actual development. For example:
fgets(str, sizeof(str), stdin);
This can help prevent the issue of buffer overflow in strings.