C while 不停止

标签 c while-loop

我只是不明白为什么这段时间没有停止:

int **movePlayer(int playerI,int playerJ,int length,int ***tab)
{
char letter;
int l;
int c =0;
int verif = 0;
int number;
//int c= 0;
while( verif == 0){
    //fflush(stdin);
    printf("Entrez la lettre correspondante à la colonne sur laquelle vous voulez jouer\n");
    scanf(" %c", &letter);
    //fflush(stdin);
    printf("Entrez le chiffre correspondante à la ligne sur laquelle vous voulez jouer\n");
    scanf(" %d", &number);
    verif = verifScan(playerI,playerJ,letter,number,tab,length);
    printf("%d", verif);
    verif = 1;
}
l = (int)letter - 65;
(*tab)[playerI][playerJ] = 'j' ;
(*tab)[number][l] = 'J';
}

我准确地说 verif 的最后一个 printf 返回 1,因为我的函数 verifScan 在这里返回 1。

verifScan 在这里,当我在 scanf 中写入 B 和 0 时返回 1:

int verifScan(int posI,int posJ,int letter, int number,int ***tab,int     length)
{
   int l;
   if(letter >= 97 && letter <= 97 + length - 1){
      l = letter - 97;
      //return 1;
   } else if(letter >= 65 && letter <= 65 + length - 1){
      l = letter - 65;
      //return 1;
   }else {
      return 0;
   }
   if(number > length - 1 || number < 0){
      return 0;
   }
   if(verifCaseLibre(tab,l,number) == 0){
      return 0;
   }

   if((abs(l - posJ) == 0 && abs(number - posI) == 1) || (abs(l - posJ) == 1 && abs(number - posI) == 0))
   {
      return 1;
   }

   return 1;
}

I admet that i have a lots of warning

请问我可以帮忙吗?谢谢。

最佳答案

问题 1

fflush 用于输出流,而不是输入流。使用 fflush(stdin) 是不正确的。来自 http://en.cppreference.com/w/c/io/fflush :

For input streams (and for update streams on which the last operation was input), the behavior is undefined.

如果您想忽略直到行尾的所有内容,您可以使用:

 int c;
 while ( (c = getc(stdin)) != '\n' && c != EOF);

我建议将其放入函数中并调用该函数。

 void ignoreLine(FILE* fp)
 {
    int c;
    while ( (c = getc(fp)) != '\n' && c != EOF);
 }

然后使用

 ignoreLine(stdin);

问题2

在调用 scanf 的格式说明符中使用 "%c" 不会跳过空格。如果您想跳过空格,请使用"%c"

  scanf(" %c", &letter);
<小时/>

您的问题很可能是由上述两者的组合引起的。

关于C while 不停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50159345/

相关文章:

c - 使用C读取RaspberryPi上的声卡数据

c - 以编程方式监视 XP 上的 CPU 负载

javascript - setTimeout 在循环中检查边界变化

java - 我的条件声明有问题

java - 迭代文本文件时嵌套 while 循环的奇怪行为

c# - 如何在 C# 中添加外部文件的数据量(流读取器)

php - 按 php 中类似的 2 个字段分组并得到总计数结果?

c - 如何调整 VirtualAlloc 分配的区域?

c - 整数加法中多余的中间存储指令

c - 导出文件 (*.h) 中使用 bool 返回类型的函数签名