【问题标题】:c scanf did not work. with file I/Oc scanf 不起作用。带文件 I/O
【发布时间】:2016-06-24 07:22:00
【问题描述】:

在 Mac OS 中使用 C,我尝试归档 I/O。

在我的代码中,如果scanf 1,尝试读取文件。

在while循环中,如果scanf 99,结束。

如果我 scanf 1,请尝试正确读取文件。

但在循环中,never next scanf,所以它是无限尝试文件读取。

我如何避免这种情况?

#include <stdio.h>

int freindFileReading();

int main(int argc, const char * argv[]) {


    while(1){
        int inputOfAct ;
        int Total_friendship_records;
        printf("Input what you want to act\n");
        printf("0  : Read data files\n");
        printf("99 : Quit\n");
        scanf("%d",&inputOfAct);
        switch(inputOfAct){
            case 1:
                printf("Reading..\n");
                Total_friendship_records = freindFileReading();
                printf("Total friendship records: %d\n",Total_friendship_records);
                break;
            case 99:
                return 0;
                break;
            default:
                printf("undefined input, retry\n");
        }
    }
    return 0;
}


int freindFileReading(){
    char * num1;
    char * num2;
    int there_is_num1=0;
    int Total_friendship_records = 0;

    FILE  *friendFile = freopen( "/Users/kimmyongjoon/Desktop/lwt/ltw1994/Project/Project/friend.txt", "r" ,stdin);

    if( friendFile != NULL )
    {
        char strTemp[255];
        char *pStr;

        while( !feof( friendFile ) )
        {
             if(strTemp[0]!='\n'){
                if(there_is_num1==0){
                    there_is_num1=1;
                    Total_friendship_records++;
                }else if(there_is_num1==1){
                    there_is_num1=0;
                }
            }
            pStr = fgets( strTemp, sizeof(strTemp), friendFile );
            printf( "%s", strTemp );
        }
        fclose( friendFile );
    }
    return Total_friendship_records;
}

【问题讨论】:

    标签: c file scanf


    【解决方案1】:

    问题出在这个循环中 -

    while( !feof( friendFile ) )
    {
        if(strTemp[0]!='\n'){
            if(there_is_num1==0){
                there_is_num1=1;
                Total_friendship_records++;
            }else if(there_is_num1==1){
                there_is_num1=0;
            }
        }
        pStr = fgets( strTemp, sizeof(strTemp), friendFile );
        printf( "%s", strTemp );
    }
    

    while(!feof()) 应该避免。在if 条件下,您尝试这样做 -

    if(strTemp[0]!='\n')
    

    因为首先没有存储在strTemp 中,所以这个条件是不正确的。

    我会建议你这样做 -

    while(fgets(strTemp,sizeof(strTemp),friendFile)!=NULL)  //read complete file
    {
         if(there_is_num1==0){
            there_is_num1=1;
            Total_friendship_records++;
         }else if(there_is_num1==1){
            there_is_num1=0;
         }
         printf( "%s", strTemp );
    }
    

    循环将一直工作,直到fgets 返回NULL。此外,当遇到换行符时,无需检查'\n' 是否为fgets 返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多