scanf() 和接受用户输入的问题

Issues with scanf() and accepting user input

我正在尝试使用 space 接收用户输入并将其存储在字符数组中。 之后,我想接受一个字符值并将其存储为一个字符。 但是,当我 运行 我的代码时,该字符的提示将被忽略,而是填充 space 。我怎样才能接受一个字符数组并且仍然允许在之后提示输入单个字符?

void main()
{
    char userIn[30];
    char findChar;


    printf("Please enter a string: ");
    scanf("%[^\n]s", userIn);

    printf("Please enter a character to search for: ");
    scanf("%c", &findChar);

    //this was put here to see why my single char wasnt working in a function I had
    printf("%c", findChar);

}

scanf("%[^\n]s", userIn);有点奇怪。 s 保证不会匹配,因为该字符将始终为 \n。此外,您应该使用宽度修饰符来避免缓冲区溢出。使用 scanf("%29[^\n]", userIn); 仅此并不能解决问题,因为下一个 scanf 将消耗换行符。有几个选项。您可以在第一个 scanf 中使用换行符:

scanf("%29[^\n]%*c", userIn);

或在下一次调用中丢弃所有空格

scanf(" %c", &findChar);

对于长度超过 29 个字符的输入行或当用户尝试将空格分配给 findChar 时,行为会有所不同,因此您使用哪种解决方案将取决于您希望如何处理这些情况。

scanf("%c", &findChar); 读取输入流中待处理的下一个字符。此字符将是停止先前转换的用户输入的换行符,因此 findChar 将设置为值 '\n',无需等待任何用户输入,并且 printf 将输出此换行符没有任何其他可见效果。

将调用修改为 scanf(" %c", &findChar) 以忽略挂起的白色 space 并从用户那里获取下一个字符,或者更可靠地编写一个循环来读取输入行的读取和忽略。

另请注意 scanf("%[^\n]s", userIn); 不正确:

    如果用户键入的输入超过 29 个字节,
  • scanf() 可能会存储超出 userIn 末尾的字节。
  • ] 之后的 s 是一个错误,字符 类 的转换格式不是 %s 转换的变体。

其他问题:

  • void 不是 main() 函数的 return 值的正确类型。
  • 此代码需要 <stdio.h> header。

这是修改后的版本:

#include <stdio.h>

int main() {
    char userIn[30];
    int c;
    char findChar;
    int i, found;

    printf("Please enter a string: ");
    if (scanf("%29[^\n]", userIn) != 1) {
        fprintf(stderr, "Input failure\n");
        return 1;
    }
    /* read and ignore the rest of input line */
    while ((c = getchar()) != EOF && c != '\n')
        continue;

    printf("Please enter a character to search for: ");
    if (scanf("%c", &findChar) != 1) {
        fprintf(stderr, "Input failure\n");
        return 1;
    }

    printf("Searching for '%c'\n", findChar);
    found = 0;
    for (i = 0; userIn[i] != '[=10=]'; i++) {
        if (userIn[i] == findChar) {
            found++;
            printf("found '%c' at offset %d\n", c, i);
        }
    }
    if (!found) {
        printf("character '%c' not found\n", c);
    }
    return 0;
}