简体   繁体   English

C-Getchar在嵌套的while循环中导致无限循环

[英]C - Getchar in a nested while loop causing infinite loop

I'm currently trying count the number of characters in a text file excluding line comments (like //comment), so I'm trying to identify the start of a comment (//) and use a while loop to read the comment until I encounter a EOF or new line character, thus I know that the comment has ended. 我目前正在尝试计算文本文件中不包括行注释(例如// comment)的字符数,因此我尝试标识注释的开始(//),并使用while循环读取注释,直到我遇到EOF或换行符,因此我知道评论已结束。 The problem is that when I'm using a double while loop() to filter out line comments, it causes an infinite loop, because it will not exit the inner while loop. 问题是当我使用double while loop()过滤掉行注释时,它会导致无限循环,因为它不会退出内部while循环。 Here is my code. 这是我的代码。 Does anyone have any ideas as to why this is happening? 有谁知道为什么会这样吗? I'm stumped. 我很沮丧

int numChars = 0;
int c = 0;
int prevc = 0;

while ((c = getchar()) != EOF) {
        if (c == '/' && prevc == c) {
            while (c != '\n' || c != EOF) {
                c = getchar();
            }
        }

    numChars++;
    prevc = c;
}

For instance, if the text file were to contain //Hello, it should output 0 chars, while if the text file contains Hello it should output 5 chars. 例如,如果文本文件包含// Hello,则应输出0个字符,而如果文本文件包含Hello,则应输出5个字符。

c != '\\n' || c != EOF c != '\\n' || c != EOF is always true. c != '\\n' || c != EOF始终为true。

It could only be false if both conditions were false, which would mean that both c == '\\n' and c == EOF were true. 如果两个条件都为假,则只能为假,这意味着c == '\\n'c == EOF都为真。 Obviously, those two cannot both be true (unless EOF were the same as '\\n' , which it isn't). 显然,这两个不能都成立(除非EOF'\\n'相同,但不是)。

You need to use && , not || 您需要使用&& ,而不是|| .

This statement is always true. 这句话总是正确的。

while (c != '\n' || c != EOF)

Hence an infinite loop. 因此,无限循环。

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

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