如何将字符一个接一个地存储在数组中,直到用户输入字符以外的输入,然后在屏幕上重现相同的内容?

How to store character in array one after another untill user enters input other than character, and then reproduce the same on the screen?

下面是我使用 a 存储用户的 a-z 字母表然后在屏幕上再现相同内容的程序。

#include <stdio.h>
#include <string.h>

int main()
{
    int const size = 26;
    int index;
    char arr[size];   // = "abcdefghijklmnopqrstuvwxyz";
    printf("\nEnter the lowercase letters\n");
    for (index = 0; index < size; index++){
        scanf_s("%c", &arr[index]);
    }

    for (index = 0; index < size; index++){
        printf("\n%c\n", arr[index]);
    }
    return 0;
}

虽然,直接存储它然后重现它对我来说更容易,但是每当我启动 运行 程序时。它接受直到字母 'm' 然后退出。我一直在试图弄清楚但找不到错误。我也在使用 Visual Studio 2013 Ultimate。我也在一行一行输入。

这是因为 "%c" 说明符正在捕获上一次调用留下的 '\n' 字符。

您可以通过使格式字符串忽略该字符来解决它。这是通过在 %c 之前添加一个明确的白色 space 来完成的

scanf(" %c", &arr[index]);

但在这种情况下,如果您简单地使用 getchar()fgetc(),效果会更好,就像这样

size_t size = 26;
int    chr;
size_t index;
char   arr[size] = {0};

chr = getchar();
for (index = 0 ; ((index < size) && (chr != EOF)) ; ++index)
 {
    arr[index] = chr;
    chr        = getchar();
 }
for (index = 0 ; index < size ; ++index)
    printf("%c\n", arr[index]);

此外,您显然和其他人一样以错误的方式使用 scanf(),即使在这种情况下不太可能出现问题,您也不会检查 return scanf() 的值,这是一个潜在的问题,因为如果 Ctrl+D 或 "Ctrl+Z (Windows OS)",则 arr[index] 将被取消初始化。