【问题标题】:How come I can't manipulate the string in fscanf为什么我不能在 fscanf 中操作字符串
【发布时间】:2020-09-18 18:22:29
【问题描述】:
#include <stdlib.h>

int main()
{
    FILE *testData;
    char gender[10] = {0};
    int age[10];
    int weight[10];
    int x = 0;

    testData = fopen("New Text Document.txt", "r");

  if(testData == NULL){
    printf("Error!");
    return (1);
}
while((fscanf(testData,"%s%s%s",gender,age,weight))!= EOF){
 printf("%s\n%s\n%s\n",gender,age,weight);
    if(gender == "M" || gender == 'M' || gender == "F"){
        printf("hi");
        }
}
fclose(testData);
return 0;
}

我不确定为什么性别实际上不知道它的字母?我完全迷失了这一点,操纵年龄和体重非常容易,我只是无法触及性别。另外,如果我把 M == 77;它也没有做任何事情

性别是单字母(F/M)

【问题讨论】:

  • a string 和 char 是不一样的,这里的gender应该是char,如果你想把它作为一个string你需要使用strcmp来解析%c。激活编译器的警告会对你有帮助
  • 一行New Text Document.txt是什么样的?
  • strcmp 是答案@Ôrel 我很感激

标签: arrays c string scanf


【解决方案1】:

选择正确的类型非常重要。 char gender 表示单个字符。 char gender[10] 表示 10 个字符的数组:一个字符串。

同样,"M" 是一个字符串,它是一个由单个 char 加上一个空字节来指示字符串结尾的数组:{ 77, 0 } 'M' 是一个单个 char,整数 77。

gender == 'M' 比较两个字符,它们只是整数。实际上,它是gender == 77。不是gender[0] == 77gender 是内存地址,一些随机整数,所以不起作用。

gender == "M" 也不起作用。 == 不会比较字符串文字,它是 undefined behavior。相反,您需要使用函数strcmpstrcmp(gender, "M") == 0.

或者您可以将gender 切换为单个char,将fscanf 切换为使用%c,然后执行gender == 'M' || gender == 'F'

具体取决于格式。


ageweight 也有问题。这些是指向 10 个整数数组的指针,但您将它们用作字符串。这只能靠运气。发生的事情是int age[10] 分配了 80 字节的内存(8 字节整数 * 10)。当用作char *(字符串)和%s 时,这是80 个字符的空间(80 个字节/每个字符1 个字节)。 C 实际上并不关心类型,它会很乐意使用你给它的任何内存,只要它适合...有时即使它不适合。

我们可以通过在读取“23”后将age 打印为整数来看到这一点(在使用int age[10] = {0}; 对其进行初始化以避免读取垃圾之后)。

printf("Ints %d %d %d\n", age[0], age[1], age[2]);  // 13106 0 0

为什么是 13106?即(十六进制)32 表示“2”,33 表示“3”,0 表示空字节。这是一个little-endian machine,所以它会反向读取:003332,十进制是 13106。

你应该做的是int age,使用%d格式,并作为指针传入。


把它们放在一起......

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

int main()
{
    FILE *testData;
    // { 0 } is more simply written as an empty string.
    char gender[10] = "":
    int age;
    int weight;

    testData = fopen("test.txt", "r");
    if(testData == NULL){
        printf("Error!");
        return (1);
    }

    // fscanf takes pointers. gender is already a pointer. age and weight are not and
    // need the & operator to take their address.
    while( (fscanf(testData, "%s%d%d", gender, &age, &weight)) != EOF){
        printf("%s\n%d\n%d\n", gender, age, weight);

        // Compare strings with strcmp
        if(strcmp(gender, "M") == 0 || strcmp(gender, "F") == 0) {
            printf("hi");
        }
    }

    fclose(testData);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2020-07-04
    相关资源
    最近更新 更多