首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不将值放置在变量中

不将值放置在变量中
EN

Stack Overflow用户
提问于 2014-09-20 23:44:19
回答 1查看 625关注 0票数 2

我在一个文件中有一个3个值(由空格分隔),我使用fscanf将其读入3个变量。由于某种原因,这些值没有被改变。当我打印这些值时,它会打印内存垃圾/我将它们的初始值设置为什么。我也试过用fget和sscanf,但是没有骰子。

守则:

代码语言:javascript
复制
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);

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-20 23:54:08

值不更改的原因是fscanf找不到与您指定的格式匹配的值。此外,不需要空间。最后,由于要将数据读入double,而不是float,所以应该使用%lf作为格式说明符。

您可以通过检查fscanf的返回值来检查是否收到了适当的项目数。

这应该可以解决这个问题:

代码语言:javascript
复制
if (fscanf(inFile, "%lf%lf%d", &costPresale, &costDoor, &numPresale) == 3) {
    printf("%.2f %.2f %d", costPresale, costDoor, numPresale);
}

演示。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25954338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档