转换字符和 fgets() 函数未按预期工作

标签 c

我试图编写代码来查找数据类型的大小,这是我的代码:

#include <stdio.h>
#include <limits.h>
#include <string.h>

int main(int argc, const char * argv[]) {
    // insert code here...

    printf("Choose one of the following types to get the relevant storage size\n(int, float, double, short, long, char: ");

    char mytype1[7] = "";
    char mytype2[4] = "int";
    char mytype3[7] = "double";
    char mytype4[6] = "short";
    char mytype5[5] = "long";
    char mytype6[5] = "char";
    char mytype7[6] = "float";
    scanf("%s", mytype1);
    // fgets(mytype1, 7, stdin);

    if (strcmp(mytype1, mytype2) ==0){
        printf("The 'int' variable size is %lu\n", sizeof(int));
    } else if (strcmp(mytype1, mytype3) ==0){
        printf("The 'double' variable size is %lu\n", sizeof(double));
    } else if (strcmp(mytype1, mytype4) ==0){
        printf("The 'short' variable size is %lu\n", sizeof(short));
    } else if (strcmp(mytype1, mytype5) ==0){
        printf("The 'long' variable size is %lu\n", sizeof(long));
    } else if (strcmp(mytype1, mytype6) ==0){
        printf("The 'char' variable size is %lu\n", sizeof(char));

    } else if (strcmp(mytype1, mytype7) ==0){
        printf("the 'float' variable size is %lu\n", sizeof(float));

    } else {
        printf("incorrect choice\n");
    }

    return 0;
}

我的问题是:

  1. 为什么 Xcode 不接受除 %lu 之外的任何转换字符,例如我已尝试使用 'int' 语句使用 '%d',但收到警告,参数类型为 'unsigned long'?

  2. scanf() 函数对我有用,但对 fgets() 函数不起作用。

据我了解,fgets()函数中的大小参数是它可以容纳的最大大小,并且不一定满足(所以如果较小的大小就可以了),那么为什么我无法使用fgets()函数代替 scanf()。

谢谢。

最佳答案

对于您的第一个问题,sizeof 返回一个 size_t 类型的值,该值通常是 unsigned long 的别名,因此为什么 "%lu" 格式有效。但是,您不应该使用该格式,而应该使用指定为具有 size_t 参数的 "%zu" ( see e.g. this printf (and family) reference ) .

至于你的第二个问题,你必须记住 fgets 可以包含字符串中的换行符(如果适合)。您必须明确检查并删除它:

if (fgets(mytype1, sizeof(mytype1), stdin) != NULL)
{
    if (mytype1[strlen(mytype1) - 1] == '\n')  // Is the last character a newline?
        mytype1[strlen(mytype1) - 1] = '\0';  // Yes, change it to the string terminator
}

关于转换字符和 fgets() 函数未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447208/

相关文章:

我的作业 C RPG 游戏

python - 使用管道将数据从 c 程序发送到 python 程序?

c++ - 枚举窗口?

c - typedef 结构体用法

c - 复制字符串数组时出现错误结果

c - 以良好的方式在 C 中分配和释放内存

c - 写入结构时出现段错误

c - 我怎样才能让 Doxygen 显示结构而不是类

c: 释放分配的对象错误

c - 在函数返回之前删除堆栈内存的选项