我怎样才能解决这个使用c在控制台中输出不正确的问题

How can I solve this problem of incorrect output in console using c

这是我的代码

int main(void) { 
  char c;
  int i = 0;
  while(i < 10) {
    c = getchar();
    printf("%c\n", c);
    i++;
  }
  return 0; 
}

我想循环 10 次并从用户那里获取输入,实际上每次只有一个字符。并将其打印回控制台。但问题出在输出

a


b


c


d


e



我循环了 10 次,但输入只有 5 次。谁能告诉我问题出在哪里?

每次获得输入

时,您都需要使用来自stdin的新行('\n')字符
#include <stdio.h>

void flush() {
  int c;
  while((c = getchar()) != '\n');
}

int main(void) { 
  char c;
  int i = 0;
  while(i < 10) {
    c = getchar();
    flush();
    printf("%c\n", c);
    i++;
  }
  return 0; 
}

getchar() 将 return 字母之间换行。你应该跳过那些。

此外,如果到达文件末尾,请停止。您需要将 c 更改为 int 以正确检查。

int main(void) { 
  int c;
  int i = 0;
  while(i < 10) {
    c = getchar();
    if (c == EOF) {
      break;
    } else if (c != '\n')
      printf("%c\n", c);
      i++;
    }
  }
  return 0; 
}

输出恰好执行了 10 次。

问题是函数 getchar 也会读取白色 space 字符,例如对应于按下的 Enter 键的换行符 '\n'

使用函数 scanf 而不是 getchar

scanf( " %c", &c );

注意符号%c 前的空格。需要跳过白色 space 个字符。

程序可以通过以下方式查找示例。

#include <stdio.h>

int main(void) 
{
    const int N = 10;
    char c;

    for ( int i = 0; i < N && scanf( " %c", &c ) == 1; i++ )
    {
        printf( "%c\n", c );
    }

    return 0;
}

如果你想使用 getchar 那么你应该将变量 c 声明为 int.

类型

在这种情况下,您的程序可以如下所示

#include <stdio.h>

int main(void) 
{
    const int N = 10;
    int c;

    int i = 0;
    while ( i < N && ( c = getchar() ) != EOF )
    {
        if ( c != '\n' )
        {
            printf( "%c\n", c );
            i++;
        }
    }       

    return 0;
}