【问题标题】:Gcc compiler can not scan a character and come out from loop and terminate program [closed]Gcc编译器无法扫描字符并从循环中出来并终止程序[关闭]
【发布时间】:2018-09-23 14:39:52
【问题描述】:

//mvt 的代码。在这个 ch 中没有被编译器扫描。 ch 用作循环的条件。它的初始值为 'y' ,如果它变为 'n' ,则循环中断。在此代码中,我询问用户是否要继续,然后按 y else n 。但不知道为什么 gcc 不等待扫描它。这是一个简单的代码,但我无法理解错误。

    int main(){
    char ch;
    temp=tm;
    ch='y';
    for(i=0;ch=='y';i++){
    printf("enter memory size for process %d",i+1);
    scanf("%d",&m);
    if(m<temp)
    {printf("memory allocated\n"); ms[n]=m; n++;
    temp-=ms[i];
     }
    else 
    {printf("memory not allocated\n"); }
https://stackoverflow.com/users/10404087/rishabh-sharma
    printf("do you want to continue");
    scanf("%c",&ch);
    }
    printf("total memory : %d\n",tm);
    printf("process \t occupied \n");
    for(i=0;i<n;i++)
        printf("%7d \t %8d \n",i+1,ms[i]);
    printf("total externel fregment : %d \n",temp);
    return 0;
    }

【问题讨论】:

  • 您将代码粘贴为问题中的文本而不是图像。
  • 使用调试器。 scanf 读入 ch 的内容是什么?然后你可以查找scanf is reading new line character
  • 请不要发代码图片,只发代码为文字。
  • 草率的介绍对所有读者来说都是无礼的。

标签: c gcc


【解决方案1】:

您必须使用flushall() 函数清除与输入流关联的所有缓冲区,并写入与输出流关联的所有缓冲区。

添加:flushall() 不是 C,而是供应商特定的扩展。

另一种选择是在%c之前使用空格


例子

char ch;
scanf(" %c", &ch);

【讨论】:

  • 在检测到EOF 之前,我会读取流中的所有chars。
  • @alk 但我认为那是额外的开销。在这种情况下,我们知道它只是遇到了回车,所以为什么我们必须通过缓冲区直到EOF,因为这会增加时间复杂度。
  • @alk:你的意思是 EOF 还是 EOL(行尾)?我建议 EOL 比 EOF 更有帮助,尽管 EOF 不一定是错误的。
猜你喜欢
  • 2015-01-05
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多