[英]Reading and Printing from a file but stuck in loop C
我試圖從文件中讀取一些數據,然后將其打印出來,但是我的代碼僅讀取第一個內容,然后陷入無限循環(在while循環中)。 我究竟做錯了什么? 我的輸出僅為Student:Abby GPA:3我正在使用Visual Studio2012。我只是在遵循我書中的一個示例。
//My data is Abbie 3.4 Oakley 3.5 Sylvia 3.6 Uwe 3.7 Ken 3.8 Aaron 3.9 Fabien 4
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
unsigned int GPA;//GPA
char student[10];//Student
FILE * cfPter;
//Check if file opened
if((cfPter = fopen("data.txt", "r")) ==NULL)
{
puts("File could not be opened");
}
//Read Contents
else
{
puts("Contents of file:\n");
fscanf(cfPter,"%s %f ", student, &GPA);
}
//While not at end Print the contents read
while(!feof(cfPter))
{
printf("Student: %s GPA: %f",student,GPA);
fscanf(cfPter, "%s %f", student, GPA);
//system("pause");
}
fclose(cfPter);
system("pause");
} //end main
您可以到達那里,但是有一些調整可以使生活更輕松。 首先,如果您的fopen
失敗,則通過提示輸入另一個文件名來解決該失敗,或者只是在此時return
( exit
)。 這樣,您的其余代碼就不會包裝在else
語句中。
接下來,我提供了為什么while (!feof(file))
總是錯誤的(從文件中讀取字符數據時)的鏈接。 閱讀輸入時,請驗證您是否收到輸入-這實際上是您需要做的所有事情。 檢查fscanf
調用的返回。
考慮到這一點,您可以執行以下操作:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void) {
float GPA = 0.0; /* GPA */
char student[10] = ""; /* Student */
FILE *cfPter = NULL;
/* open file/validate file is open */
if (!(cfPter = fopen ("data.txt", "r"))) {
fprintf (stderr, "error: file open failed 'data.txt'.\n");
return 1;
}
/* Read Contents */
while (fscanf (cfPter, " %9s %f", student, &GPA) == 2)
printf ("Student: %-10s GPA: %.2f\n", student, GPA);
fclose (cfPter);
return 0; /* main is type 'int' and returns a value */
}
示例data.txt
$ cat data.txt
Abbie 3.4 Oakley 3.5 Sylvia 3.6 Uwe 3.7 Ken 3.8 Aaron 3.9 Fabien 4
使用/輸出示例
$ ./bin/feofissue
Student: Abbie GPA: 3.40
Student: Oakley GPA: 3.50
Student: Sylvia GPA: 3.60
Student: Uwe GPA: 3.70
Student: Ken GPA: 3.80
Student: Aaron GPA: 3.90
Student: Fabien GPA: 4.00
( 請注意,雖然MS會讓您從很早以前就使用void main
,但main
定義為int
類型並返回一個值。)
同樣要pause
,通常在Windows上#include <conio.h>
並調用getch();
以防止關閉終端窗口。 您可以嘗試任何一種方式。 如果您有任何問題,請告訴我。
我也在做這個工作,有人告訴我嘗試使用strcmp()逐行讀取文件,直到找到所需的行? 我正在考慮這個想法,但是還沒有弄清楚之后如何讀取GPA。
避免在fscanf中讀取不同類型的日期的一種計划是始終將char數據讀取到本地char數組中。 然后使用sscanf將其轉換為所需的數據類型。 這使您可以在fscanf和sscanf之間添加數據檢查。 這將避免fscanf不讀取任何內容(轉輪),並且永遠不會陷入困境
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.