scanf()函数中while循环不会终止? [英] scanf() in while loop not terminating?

查看:599
本文介绍了scanf()函数中while循环不会终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个while循环,在整数集合的输入扫描。它可以扫描并打印所有的数字与...结尾,并跳到下一行。然而,脚本不:过去执行while循环和打印测试

例如,我输入:
3 44 62 1

它打印:
3 ...

44 ...

62 ...

1 ...

当它应该打印:
3 ...

44 ...

62 ...

1 ...

TEST

 而(scanf函数(%d个,&安培;!N)=  -  1){
    X [i] = N;
    我++;    的printf(%d个,N);
    的printf(... \\ n);
}的printf(TEST);

我在做什么错了?


解决方案

  1. scanf函数(%d个,&安培; N)!= 1 是错误的。它应该是 scanf函数(%d个,&安培; N)== 1

  2. 您在期望的循环结束,只是因为你打进去吗?作为写入,如果scanf的无法读取的一些由于到达输入文件的末尾的程序将只停止。如果你是在Unix上,你可以按Ctrl-D端子信号EOF。如果您使用的是Windows,它是按Ctrl-Z键。 (另外,不要依赖 EOF 是-1;它不是便携式)

I have a while loop that scans in an input set of integers. It scans and prints all of the numbers with "..." at the end and skips to the next line. However, the script does not: execute past the while loop and print TEST.

For example, I enter: 3 44 62 1

It prints: 3...

44...

62...

1...

When it should print: 3...

44...

62...

1...

TEST

while(scanf("%d", &n) != -1) {
    x[i] = n;
    i++;

    printf("%d", n);
    printf("...\n");
}

printf("TEST");

What am I doing wrong?

解决方案

  1. scanf("%d", &n) != 1 is wrong. It should be scanf("%d", &n) == 1.
  2. You're expecting the loop to end just because you hit enter? As written, your program will only stop if scanf fails to read a number due to reaching the end of the input file. If you're on Unix, you can signal EOF from the terminal by hitting Ctrl-D. If you're on Windows, it's Ctrl-Z Enter. (Also, don't rely on EOF being -1; it's not portable.)

这篇关于scanf()函数中while循环不会终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆