【问题标题】:C scanf stop in whileC scanf 在 while 中停止
【发布时间】:2018-03-10 15:47:16
【问题描述】:

我需要在代码中更正什么以便在用户停止输入数据时停止循环?

while(scanf("%i", &num)){   
    printf ("%#o %d 0x%X\n", num, num, num);<br/>
}

【问题讨论】:

  • 你的代码是 C 而不是 C++!
  • when the user stops entering data 什么时候?
  • 看起来您的代码已经按照您的要求执行了。
  • 我测试过。我停止了写作,程序仍然有效

标签: c


【解决方案1】:

你可以用这个

#include<stdio.h>
int main(){
    int num;
    printf("Enter -1 for termination:");
while(scanf("%i", &num)>0 ){
        if(num<0)
        break;
  printf ("%#o %d 0x%X\n", num, num, num);

}

return 0;
}

如果您输入 -1 或任何字符,则会发生终止:

Enter -1 for termination:3
03 3 0x3
6
06 6 0x6
9
011 9 0x9
k

Process returned 0 (0x0)   execution time : 8.779 s
Press any key to continue.

【讨论】:

    【解决方案2】:

    您的scanf("%i", &amp;num) 仅在用户按回车键/回车键时返回,前提是他们之前在终端中输入了一些非空白字符。如果用户在空行上按回车,函数将继续等待非空白字符。

    如果您键入一个非数字值,在您按下回车键之前,您将退出while 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多