【发布时间】:2014-03-09 19:50:20
【问题描述】:
这是我的 C 编程课的家庭作业。
给我一个文本文件,有两个数据列;第一列是age;第二列是avgprice。我能够很好地读取和打印这些值。但是,由于某种原因,age 和 avgprice 在输出中被翻转。我不知道为什么。
这里是代码
#include "stdafx.h"
#include <stdio.h>
int main() {
double age, avgprice; //age = 1st column, avgprice = 2nd column
FILE *corolla; //ptr for file
char eof; //needed for end of file check
corolla = fopen("C:/Users/Nate/Downloads/DataFiles/corolla.txt", "r");
if (corolla == NULL) { //makes sure the file exists
printf("File does not exist!\n");
return 0; //prevents crashing
}
else {
printf("Age \t\t Average Price\n"); //header for data when printed
/*prints values until we're at the end of the file*/
while (fscanf(corolla, "%c", &eof) != EOF) {
fscanf(corolla, "%lf %lf", &age, &avgprice); //scans in data from file
printf("%.1f \t\t $%.2f\n", age, avgprice); //prints data from file
}
}
fclose(corolla); //closes file
return 0;
}
这是输出的样子
这让我很困惑,因为我已经使用这种确切的格式对其他数据文件做同样的事情——没有问题。由于某种原因,这个文件有困难。
这是我应该阅读的数据文件。我已将它上传到我的 Dropbox,这样您就可以在必要时检查格式。 Corolla.txt
【问题讨论】:
-
诚实地说这是家庭作业并且您已发布代码,因此您会获得 +1。
-
你的第一个
fscanf吞下了“1”。之后,您的输入是错误的,因为fscanf不知道换行符。 (嗯,确实如此,但它像对待任何其他空间一样对待它们。) -
参见例如关于如何使用 fscanf stackoverflow.com/a/3351926/297323
标签: c file while-loop