首页 > 解决方案 > Not adding correct data in a file in C

问题描述

So, I am trying to take a user input and add it to a file, however when I get to the phone number, I write 123123123, so 9 numbers because thats how phone numbers work where I live. But when I check the file that I put this data into, the number is 123122944 ?? why?

char firstName[32];
    char lastName[32];
    long int dateofbirth;
    long int phoneNumber;
    char wantItForFree[3];

printf("Record #%d\n", i);
        printf("Enter first name: ");
        scanf("%s", firstName);
        printf("Enter last name:  ");
        scanf("%s", lastName);
        printf("Enter dateofbirth in YYYYMMDD format:  ");
        scanf("%ld", &dateofbirth);
        printf("Enter phone number in 36XXXXXXXXX format:  ");
        scanf("%ld", &phoneNumber);
        printf("Do you want the vaccination for free:  ");
        scanf("%s", wantItForFree);
        printf("\n");

        
        
        fprintf(file, "%d\t%s\t%s\t%ld\t%ld\t%s\n", i, firstName, lastName, dateofbirth, phoneNumber, wantItForFree);

Here is the code. What is happening? btw i declared phoneNumber as a long int.

The input is

john 
doe 
20010613 
123123123 
yes

and the output is

john doe 20010613 123122944 yes

标签: c

解决方案


这段代码中至少出现了 2 个常见错误。%s首先,转换说明符必须始终有一个最大字段宽度。如果没有给出最大字段宽度,scanf则不比gets. 其次,总是需要检查scanf返回的值。如果scanf未成功匹配转换说明符,则不会将数据写入相应的参数。如果相应的参数未初始化,则对该变量的后续读取会导致未定义的行为。例如:

char firstName[32];
if( scanf("%31s", firstName) != 1 ){
        fprintf(stderr, "Invalid input\n");
        exit(EXIT_FAILURE);
}

这里犯的第三个常见错误是尝试将 3 个字符串存储在大小为 3 的数组中,但 IMO 这是一个次要错误,可以通过修复 2 个主要错误来解决。


推荐阅读