C 编程中 (char)getchar() 的函数

rew*_*wed 2 c

我的朋友问我(char)getchar()他​​在一些在线代码中找到了什么,我用谷歌搜索并发现它被使用的结果为 0,我认为常规用法只是ch = getchar(). 这是他找到的代码,谁能解释一下这个函数是什么?

else if (input == 2)
{
    if (notes_counter != LIST_SIZE)
    {
        printf("Enter header: ");
        getchar();
        char c        = (char)getchar();
        int tmp_count = 0;
        while (c != '\n' && tmp_count < HEADER)
        {
            note[notes_counter].header[tmp_count++] = c;
            c = (char)getchar();
        }
        note[notes_counter].header[tmp_count] = '\0';
        
        printf("Enter content: ");
        c         = (char)getchar();
        tmp_count = 0;
        while (c != '\n' && tmp_count < CONTENT)
        {
            note[notes_counter].content[tmp_count++] = c;
            c = (char)getchar();
        }
        note[notes_counter].content[tmp_count] = '\0';
        
        printf("\n");
        notes_counter++;
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*hil 5

(char)getchar()是一个错误。切勿使用它。

getchar返回一个int,它可以是unsigned char读取的字符的值,也可以是 的值EOF(负数)。如果将其转换为,您将失去和 映射到相同值的某些字符char之间的区别。EOFchar

的结果getchar应始终分配给一个int对象,而不是一个char对象,以便保留这些值,并且应测试结果以查看它是否在EOF程序假定已读取字符之前。由于程序用于c存储 的结果getcharc因此应声明为int c, not char c

编译器可能会发出警告,c = getchar();因为该赋值将 an 隐式转换int为 a char,这可能会丢失如上所述的信息。(此警告并不总是由编译器发出;它可能取决于所使用的警告开关。)该警告的正确解决方案是更改cint,而不是插入到 的强制转换char

关于转换:C 标准允许char有符号或无符号。如果它是无符号的,则将把由返回的值(char) getchar()转换为某个非负值,该值与字符值之一相同。如果它是有符号的,则将以实现定义的方式将一些字符值转换为,并且其中一些转换可能会产生与 相同的值。EOFgetchar()(char) getchar()unsigned charcharEOF