【发布时间】: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;
}
【问题讨论】: