fscanf不在变量中放置值
我在一个文件中有3个值(用空格分隔),我正在使用fscanf将其读入3个变量。由于某些原因,这些值没有被更改。当我打印这些值时,它会打印内存垃圾/无论我将它们的初始值设置为什么。我也尝试过将FGET与sscanf结合使用,但没有骰子 守则:fscanf不在变量中放置值,c,fgets,scanf,C,Fgets,Scanf,我在一个文件中有3个值(用空格分隔),我正在使用fscanf将其读入3个变量。由于某些原因,这些值没有被更改。当我打印这些值时,它会打印内存垃圾/无论我将它们的初始值设置为什么。我也尝试过将FGET与sscanf结合使用,但没有骰子 守则: int numPresale; // The number of presale tickets sold double costPresale; // The cost of presale tickets double costDoor; // T
int numPresale; // The number of presale tickets sold
double costPresale; // The cost of presale tickets
double costDoor; // The cost of tickets sold at the door
// Opens the file. Exits program if it can't
if((inFile = fopen(fileName, "r")) == NULL) {
printf("Unable to open the input file '%s'\n", fileName);
exit(EXIT_FAILURE);
}
// Parse for information
fscanf(inFile, "%.2f %.2f %d", &costPresale, &costDoor, &numPresale);
printf("%.2f %.2f %d", costPresale, costDoor, numPresale);
fclose(inFile);
我肯定我犯了一些典型的新手错误,但我在网上找不到任何答案。提前感谢您的帮助 值不更改的原因是
fscanf
找不到与指定格式匹配的值。此外,不需要空间。最后,由于您正在将数据读入double
,而不是float
,因此应该使用%lf
作为格式说明符
您可以通过检查fscanf
的返回值来检查是否收到了正确数量的项目
这将解决此问题:
if (fscanf(inFile, "%lf%lf%d", &costPresale, &costDoor, &numPresale) == 3) {
printf("%.2f %.2f %d", costPresale, costDoor, numPresale);
}
此外,请始终检查返回值。并使用完整警告:
-Wall-Wextra-pedantic
.2f
不需要两个位置。对于scanf
,它只是一个无效的格式字符串。
字符不用于scanf
格式。