c - 为什么我的程序在读取 txt 文件之前就停止了?

标签 c visual-studio-2010 file printf fopen

我的代码在读取文件之前一直关闭,我在它关闭的地方做了评论。有谁知道为什么它不起作用?我把它给我的讲师看,但她无法弄清楚,然后她不得不离开,所以我想知道这里是否有人能弄清楚!

#include <stdio.h>
#include <stdlib.h>
#define RESULT_MAX = 100;
#define RESULT_MIN = 0;

int main() 
{

    int studentId;
    char firstName[20];
    char lastName[20];
    int result;

    FILE *fPtr;

    if ((fPtr = fopen("student.txt", "w")) == NULL)
    {
            printf("File could not be opened\n");
            //exit(0);
    }
    else
    {
        printf("Enter the Id, first name, last name and result\n");
        scanf("%d %s %s %d", &studentId, firstName, lastName, &result);
        while(!feof(stdin) )
        {
            fprintf(fPtr, "%d %s %s %d\n", studentId, firstName, lastName, result);
            scanf("%d %s %s %d", &studentId, firstName, lastName, &result);
        }

        fclose(fPtr);
    }//else end

// MY PROGRAM ENDS HERE AND WONT CONTINUE!


    if ((fPtr = fopen("student.txt", "r")) == NULL)
    {
            printf("File could not be opened\n");
            //exit(0);
    }
    else
    {
        printf("Id, first name, last name, result ");
        fscanf(fPtr, "%d %s %s %d", &studentId, firstName, lastName, &result);

        while(!feof(fPtr) )
        {
            printf("%d %s %s %d \n", studentId, firstName, lastName, result);
            fscanf(fPtr, "%d %s %s %d", &studentId, firstName, lastName, &result);

        }//end while
    fclose( fPtr );
    }//end if




}

最佳答案

the problem is actually the line: 'while(!feof(stdin) )'  
because feof() only becomes valid when the program 
tries to read past the end of the 'stdin' file.   

This is something that cannot be accomplished

suggest 
modifying the program to:
1) read into a local buffer[] array, in a loop, 
2) using fgets() as the loop control
3) have a leading 'q' (or similar) as an indication of having read all input
4) output a prompt for every input line
5) if going to parse the fields, parse them using 
   strtok()/atoi() strncpy() strncpy() atoi()
   or perhaps
   sscanf()
6) check first char of input buffer[] for the end marker (the 'q' above)
   to exit the input loop before parsing

there is a similar problem with the 
loop reading the file
I.E. do not use feof() for loop control
    rather use fgets()

to differentiate each line of input written to the file, modify
the fprintf(fPtr, ... ) format string to include a trailing '\n'

关于c - 为什么我的程序在读取 txt 文件之前就停止了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29318773/

相关文章:

c - 堆代码行解释

c++ - Win32 处理来自 Rich Edit 控件的 WM_NOTIFY 消息

python - 用python分割文件中的文本

java - 从特定单词后开始读取文件

python - 使用 Python 对文本文件进行排序

c++ - C - 将扫描码集 1 转换为 ASCII

c++ - 分析用 C 或 C++ 编写的程序

c# - 在 winform exe 中更改组合框选择时抛出异常,在 Debug模式下工作正常

c++ - 线程更新类对象

windows - 如何从网络共享调试 Visual Studio 2010 中的解决方案?