c - 正确的字符处理

标签 c char scanf fflush

当使用 gcc 编译到 Linux 时,每次用户输入任何答案时,程序都会在其他迭代中到达代码的相同部分,但不会等待用户的输入,而是向 scanf 函数提供换行符,让程序打印“我不明白!”每次......程序都能工作,但我仍然不希望它写“我不明白!”,而与用户的回答无关。 这是代码的具体部分。

do
{
    printf("\n\nAnswer: (y/n) ");
    scanf("%c", &ans);
    //printf("\n->%c<-\n", ans); //just for debugging
    if (ans == 'y')
    {
        age += v[0];
    }
    else if (ans != 'n')
    {
        printf("\nI don't get it!\n");
    }
} while (ans != 'y' && ans != 'n');

以下是声明:
字符 v[64];
查安斯;

(这个 do..while 循环位于“for”内部) 更令我困惑的是,该程序在 Windows 上的编译和运行完全符合我的预期......(使用 MinGW) 我尝试在 scanf 之前和/或之后使用 fflush(stdin) ,但没有帮助。 一个重要的观察结果是,当它第一次遇到这个问题时,它会按预期行事。

(before the user answers)
Answer: (y/n)
I don't get it! // this gets written every time but the first

Answer: (y/n) n

You are 21 years old!

如果用户写入无效输入:

Answer: (y/n) w

I don't get it!

Answer: (y/n) // this line and the next one should simply not be printed
I don't get it!

Answer: (y/n)
//(now it waits for user input)

有什么想法吗?

编辑

已修复: (我声明了一个额外的 char buf[50] )

do
{
    printf("\n\nAnswer: (y/n) ");
    fgets(buf, 50, stdin);
    sscanf(buf, " %c", &ans);
    if (ans == 'y')
    {
        age += v[0];
    }
    else if (ans != 'n')
    {
        printf("\nI don't get it!\n");
    }
} while (ans != 'y' && ans != 'n');

有人可以告诉我 scanf 有什么问题吗?

最佳答案

停止使用scanf。现在。

改用fgets(buffer, BUFLEN, stdin)。然后使用sscanf解析结果。它会更加健壮,并且会解决你的问题。

我听说在格式说明符周围添加空格也有帮助,因为它消除了残留的“空白”。 scanf("%c", &ans); 但我不喜欢它。

更新这是一段代码,我相信它的运行方式与您想要的一样(我用 printf 语句替换了内部结构,但您明白了;我还替换了你的 if 带有 switch - 我认为它更干净):

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

#define N 100

int main(void) {

  char buf[N];
  char ans;
  int ii;

  for (ii = 0; ii < 10; ii++)
  {
    do
    {
      printf("\n\nAnswer: (y/n) ");
      fgets(buf, N, stdin);
      sscanf(buf, "%c", &ans);
      printf("==%c==", ans);
      switch(ans)
      {
      case 'y':
        printf("\nYou said yes :-)\n");
        break;
      case 'n':
        printf("\nYou said no :-(\n");
        break;
      default:
        printf("\nI don't get it!\n");
      }
    } while (ans != 'y' && ans != 'n');
  }
}

关于c - 正确的字符处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21742440/

相关文章:

c - 从内存位置保存和检索值

C++ - 如何将 char 附加到 char[]?

C 扫描输入字符串保存到错误的变量

c - 如何读取未知长度的输入字符串?

c++ - 使用缓存内存。映射技术

C 中的编译错误只是因为缩进?

c - 具有不同大小成员的 union 数组

mysql - 为什么我应该为 MySQL 中的 varchar 选择 255 以外的任何长度?

java - For-each并分配给二维数组Java

C 编程 - 限制用户输入一定数量的字符