我在一个文件中有一个3个值(由空格分隔),我使用fscanf将其读入3个变量。由于某种原因,这些值没有被改变。当我打印这些值时,它会打印内存垃圾/我将它们的初始值设置为什么。我也试过用fget和sscanf,但是没有骰子。
守则:
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);我肯定我犯了一些典型的新手错误,但我在网上找不到任何答案。提前感谢您的帮助!
发布于 2014-09-20 23:54:08
值不更改的原因是fscanf找不到与您指定的格式匹配的值。此外,不需要空间。最后,由于要将数据读入double,而不是float,所以应该使用%lf作为格式说明符。
您可以通过检查fscanf的返回值来检查是否收到了适当的项目数。
这应该可以解决这个问题:
if (fscanf(inFile, "%lf%lf%d", &costPresale, &costDoor, &numPresale) == 3) {
printf("%.2f %.2f %d", costPresale, costDoor, numPresale);
}演示。
https://stackoverflow.com/questions/25954338
复制相似问题