从文件读取和打印但卡在循环C中 [英] Reading and Printing from a file but stuck in loop C

查看:237
本文介绍了从文件读取和打印但卡在循环C中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从文件中读取一些数据,然后将其打印出来,但是我的代码仅读取第一个内容,然后陷入无限循环(在while循环中).我究竟做错了什么? 我的输出是Student:Abby GPA:3 我正在使用Visual Studio 2012. 我只是在跟随我书中的一个例子.

I'm trying to read some data from a file then print it out but My code is only reading the first content and then gets stuck in an infinite loop (in the while loop). What am I doing wrong? My output is just Student: Abby GPA: 3 I'm using Visual Studio 2012. I am just following an example from my book.

//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语句中.

You are getting there, but a couple of tweaks can make life easier. First, if your fopen fails, either handle the failure by prompting for another file name, or simply return (exit) at that point. That way the rest of your code isn't wrapped inside an else statement.

接下来,我提供了为什么while (!feof(file))总是错误的链接(从文件中读取字符数据时).阅读输入时,请验证您是否收到输入-这实际上是您需要做的所有事情.检查您的fscanf通话的回报.

Next, I provided the link for why while (!feof(file)) is always wrong (when reading character data from a file). When you read input, validate you received input -- that is really all you need to do. Check the return for your fscanf call.

考虑到这一点,您可以执行以下操作:

With that in mind, you could do something similar to the following:

#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

( note ,虽然MS允许您使用很久以前的void main,但main被定义为类型int并返回一个值.)

(note while MS will let you use void main from long ago, main is defined as type int and returns a value. )

对于pause,通常在Windows上也要#include <conio.h>并调用getch();,以防止终端窗口关闭.您可以尝试任何一种方式.如果您有任何问题,请告诉我.

Also to pause, you generally #include <conio.h> on windows and call getch(); to prevent the terminal window from closing. You can try it either way. Let me know if you have questions.

这篇关于从文件读取和打印但卡在循环C中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆