Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
fscanf不在变量中放置值_C_Fgets_Scanf - Fatal编程技术网

fscanf不在变量中放置值

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

我在一个文件中有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);

我肯定我犯了一些典型的新手错误,但我在网上找不到任何答案。提前感谢您的帮助

值不更改的原因是
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
格式。