How to input characters one by one in the C language?
In C language, you can use looping structure to input elements of a character array one by one. The specific steps are as follows:
- Define a character array variable to store the input characters.
- Utilize a looping structure (such as a for loop or while loop) to input the elements of the character array one by one.
- In each iteration, use the scanf function or getchar function to obtain a character and store it in the corresponding position of an array.
- After the loop is finished, the character array will store the characters inputted one by one.
Here is an example code demonstrating how to input characters in an array one by one.
#include <stdio.h>
int main() {
// 定义字符数组
char str[100];
int i;
// 逐个输入字符数组的元素
printf("请输入一个字符串:\n");
for (i = 0; i < 100; i++) {
scanf("%c", &str[i]);
// 如果输入的字符为换行符,则结束输入
if (str[i] == '\n') {
break;
}
}
// 输出字符数组
printf("输入的字符串为:\n");
for (i = 0; i < 100; i++) {
// 如果字符为换行符,则结束输出
if (str[i] == '\n') {
break;
}
printf("%c", str[i]);
}
return 0;
}
In the above example code, we defined a character array ‘str’ with a size of 100. We then used a for loop to input characters one by one. During each iteration, the ‘scanf’ function was used to get a character and store it in the corresponding position of the character array. The input stops when a newline character is entered. Finally, we used a for loop to output the characters in the array one by one until a newline character is encountered.