简体   繁体   English

C:如何在一次使用scanf的同时从键盘或文件获取输入结束时如何停止循环

[英]C : How to stop the loop when getting the end of input from keyboard or file while using scanf one char at a time

void main(void)
{
    char character;

    do {
        scanf("%c", &character);
        printf("%c", character);
    } while (character != EOF);
}

I'm going to process the input character by character, and I am only allowed to use scanf(). 我将逐个字符地处理输入,并且只允许使用scanf()。 However, the while loop does not stop. 但是,while循环不会停止。 Since I may need to process the input with multiple-line strings, it is impossible to add one more condition: character != '\\n'. 由于我可能需要用多行字符串处理输入,因此不可能再添加一个条件:字符!='\\ n'。 Can somebody help me with this problem? 有人可以帮我解决这个问题吗? Thanks! 谢谢!

You have an incorrect expectation. 您的期望不正确。 When scanf() encounters the end of the input before either matching an input item or recognizing a matching failure, it returns EOF . scanf()在匹配输入项或识别出匹配失败之前遇到输入结尾时,它将返回 EOF Under no circumstance does it modify the value of the datum associated with an input item that has not been matched. 在任何情况下都不会修改与未匹配的输入项关联的基准值。

You are ignoring scanf 's return value, which is generally a perilous thing to do, and instead testing whether scanf records EOF in the object associated with the input item, which, in your particular case, it must not ever do. 你是忽略scanf的返回值,通常是做危险的事情,而是测试是否scanf记录EOF与输入项,其中,在特定情况下,它不能永远做关联的对象。

For a start it should be int main... 首先应该是int main...

Also you need to check the return value from scanf - please read the manual page. 另外,您需要检查scanf的返回值-请阅读手册页。

Taking this into account, the code should look like this 考虑到这一点,代码应如下所示

#include <stdlib.h>
#include <stdio.h>
int main()
{
    char character;

    while (scanf("%c", &character) == 1) {
       if (character != '\n) {
         printf("%c", character)
       }
    }
    return EXIT_SUCCESS;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM