c - 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
解决方案
这段代码中至少出现了 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 个主要错误来解决。
推荐阅读
- select - 根据来自 2 个不同命中级别数据 Bigquery 的值选择 VISITID
- html - 单击汉堡菜单后试图显示我的菜单。汉堡菜单以一定宽度显示
- google-sheets - 您如何在 Google Sheet 上使用两个日期条件进行 INDEX MATCH
- swift - 如何:修复 App Delegate 中的 UIApplication 打开 URL 方法
- r - 设置 RStudio 快捷方式显示错误的键盘符号(矩形)
- java - 如何从二叉搜索树中删除字符串
- mysql - 通过 ODBC 连接检索的表情符号数据显示为问号
- entity-framework - 具有最大子记录属性的实体框架模型
- java - 如何调用 readStudents 方法?
- reactjs - react-testing-library材料-ui滑块