-1
我正在嘗試打開一個文件進行讀取,並計算其內部的emptylines數量以及單詞(for,while,do/while)在那裏的次數。對於func4它的作品,但它不工作在func2,我不知道爲什麼?計數函數不能得到結果還是什麼?爲什麼從文件中讀取並打印到屏幕不起作用? C
//func2
void ShowResult() {
char str[MAX], inputFileName[50];
int fix, loopF=0, loopW=0, loopDW=0, empty=0;
FILE *fp;
system("cls"); // clears the screen
printf("\n Type destination or the name of the result file.\n");
fflush(stdin);
fgets(inputFileName, 50, stdin);
fix=strlen(inputFileName)-1; // checks if a newline exist and removes it
if(inputFileName[fix]=='\n')
inputFileName[fix]='\0';
if((fp = fopen(inputFileName, "r"))==NULL) {
printf(" Cannot open file.\n");
return;
}
while(fgets(str, MAX, fp)) { // read line by line in file
Count(str, &loopF, &loopW, &loopDW, &empty);
}
fclose(fp);
printf("---------------------\n");
printf(" Empty lines: %d \n\n", empty);
printf(" Number of loops:\n");
printf(" For: %d \n", loopF);
printf(" While: %d \n", loopW);
printf(" Do/While: %d \n", loopDW);
printf("---------------------\n");
return;
}
//Count func to calculate stuff
void Count(char *str, int *loopF, int *loopW, int *loopDW, int *empty) {
int i, lines;
char *p;
if(choice=='4' || choice=='1' || choice=='3'){
for(i=0; i<strlen(str); i++) {
// count loops
if(str[i]=='f' && str[i+1]=='o' && str[i+2]=='r') {
(*loopF)++;
}
if(str[i]=='w' && str[i+1]=='h' && str[i+2]=='i' && str[i+3]=='l' && str[i+4]=='e') {
(*loopW)++;
}
if(str[i]=='d' && str[i+1]=='o') {
(*loopDW)++;
if((*loopDW)>=1) (*loopW)--;
}
}
// count empty lines
p=str;
lines=0;
while(*p!='\n'){
if(*p!=' ') {
lines=1;
}
p++;
}
if(!lines) {
(*empty)++;
lines=0;
}
}
}
//func4
void PrinttoScreen() {
char str[MAX];
int loopF=0, loopW=0, loopDW=0, empty=0;
system("cls"); // clears the screen
printf(" Type a program here. Ctrl+Z and enter to stop.\n");
fflush(stdin);
while((fgets(str, MAX, stdin))!=NULL){ // read line by line in stdin
Count(str, &loopF, &loopW, &loopDW, &empty);
}
printf("---------------------\n");
printf(" Empty lines: %d \n\n", empty);
printf(" Number of loops:\n");
printf(" For: %d \n", loopF);
printf(" While: %d \n", loopW);
printf(" Do/While: %d \n", loopDW);
printf("---------------------\n");
}
請使用調試器來縮小/解決您的問題。 – UnholySheep
歡迎來到Stack Overflow! ['fflush(stdin);'是未定義的行爲,不要這樣做](http://stackoverflow.com/a/38325926/2173917)。 –
'choice'沒有在您提供的代碼中聲明。如果您想幫助調試您的代碼,請提供[mcve]。 –