我正在尝试打开一个文件进行阅读,并计算其中的空行数以及单词(for,while,do / while)的次数。对于func4它可以工作,但它不在func2工作,我不知道为什么?是否计算功能无法获得str或什么?
//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");
}
答案 0 :(得分:1)
找到答案:if(choice=='4' || choice=='1' || choice=='3')
需要更改为:if(choice=='4' || choice=='1' || choice=='3' || choice=='2')