繁体   English   中英

如何使用 c 在控制台中解决此错误 output 的问题

[英]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 次并从用户那里获取输入,实际上每次只有一个字符。 并将其打印回控制台。 但问题出在 output

a


b


c


d


e



我循环了 10 次,但输入只有 5 次。 谁能告诉我有什么问题?

getchar()将返回字母之间的换行符。 你应该跳过那些。

此外,如果您收到文件结尾,请停止。 您需要将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; 
}

output 正好执行了 10 次。

问题是 function getchar 还读取空白字符,例如对应于按下的键 Enter 的换行符'\n'

而不是 getchar 使用 function scanf like

scanf( " %c", &c );

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

该程序可以看起来例如以下方式。

#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;
}

每次获得输入时,您都需要从标准输入中使用新行 ('\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; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM