c - 不确定为什么 while 循环在使用 scanf 时工作不同

标签 c

我是学习 C 的新手,据我所知,我知道如果有人给出诸如 while (1 == 1) 之类的条件,while 循环将永远运行下去。这将成为一个永远的循环。

但是在阅读一本书时,我注意到一个代码,例如

#include<stdio.h>

int main() {

    char a;
    int started = 0;
    puts("Scanning\n");
    while (scanf("%s[^\n]",&a) == 1)
    {
        if (a >= 65 && a <= 90)
        {
            printf("Char is capital\n");
        }
        else
        {
            printf("Not cap.\n");
        }

    }
    puts("Done\n");
    return 0;


}

命令行 => char.exe < file.txt

它从 stdin 获取输入,但 scanf 返回参数的数量,即 1,所以条件应该变为 while (1 == 1)

但为什么这不是一个永远的循环,而是在读取文件后存在?

谢谢

最佳答案

char a;
...
while (scanf("%s[^\n]",&a) == 1)

你的格式是无效的,因为专用于一个字符串,而你只想读取一个字符,所以你至少要从字符中写出产生未定义行为的结尾空字符

char a;
...
while (scanf(" %c",&a) == 1)

并注意格式中的空格,如果要管理所有字符,请将其删除

 if (a >= 65 && a <= 90)

使用ASCII码是错误的,这样不可读,不兼容非ASCII

你可以做到

if (a >= 'A' && a <= 'Z')

或者更好地使用 isupper ( <ctype.h> ) 因为它不能保证大写字母是连续的

您的 printf 可以替换为 puts 删除字符串中的\n,或者 fputs,没有 printf 打印一个简单的字符串(没有 % 和 arg)

But why this is not a forever loop and exists after reading the file?

scanf 在 EOF 时不返回 1,因此循环在 EOF 时停止,关于 scanf 系列:

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

关于c - 不确定为什么 while 循环在使用 scanf 时工作不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56581647/

相关文章:

C;内联汇编语法错误 "Expected string literal before numerical constant"

c - 在函数中使用结构的不同成员的最有效方法?

c - 在函数声明中将指针声明为参数的 3 种方法是什么?

c - fprintf 后文件指针设置为 NULL

c++ - curl_easy_perform() 失败 : failed FTP upload (the STOR command) error

c语言中将用户从root更改为nobody后无法生成核心文件

c - 有没有办法不用打开直接从一个文件夹复制文件到另一个文件夹

c - 赋值 <指向常量数组的指针> = <指向数组的指针> : incompatible pointers

c++ - 从 C/C++ 和参数在 GnuPG 中生成公钥/私钥

c - 使用 prctl PR_SET_NAME 设置进程或线程的名称?