在我的程序中,我要求用户输入一系列带空格的数字。这是我实现的代码:
char cinput,c=' ';
Printf("type numbers:\n");
scanf("%c",&cinput);
const char *input;
input = &cinput;
int length = strlen(input);
for (int i = 0; i < length; i++)
{
printf("%c",input[i]);
}
假设我的输入是“1 2 3”,当我尝试打印输入[1]时,我无法获得值2。重要的是要注意,我不知道序列中的数字总数,因此我无法定义数组。
如果有一种方法可以使用 while 循环读取字符序列,我将不胜感激。
请注意,该程序必须仅使用C编程语言编写。
在我的安眠药生效之前,我会告诉你你应该做什么:
char input[256]; // An array of multiple characters
// Read one whole line of input, including the ending newline
// Will not read more than 255 characters though
if (fgets(input, sizeof input, stdin) == NULL)
{
printf("Error reading the input\n");
exit(EXIT_FAILURE);
}
// Now we have a null-terminated sequence of characters in
// the array input.
// Loop over the array, one character at a time, until we get to the end
// (the end is when there's the null-terminator character)
for (size_t i = 0; input[i] != '\0'; ++i)
{
// If the current character is a space (space, tab, newline, etc.)
// then skip it by continuing the loop with the next character
if (isspace(input[i]))
{
continue;
}
// Here we have a non-space character at index i, print it
printf("input[%d] = '%c'\n", i, input[i]);
}
注释应该足以解释代码的每个部分的作用。