gpt4 book ai didi

c - 为什么从文件读取并打印到屏幕不起作用? C

转载 作者:行者123 更新时间:2023-11-30 19:10:23 25 4
gpt4 key购买 nike

我正在尝试打开一个文件进行读取,并计算其中的空行数以及单词(for、while、do/while)出现的次数。对于 func4 它可以工作,但它不能在 func2 中工作,我不知道为什么?是 count 函数无法获取 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");
}

最佳答案

找到答案:if(choice=='4' || choice=='1' || choice=='3')需要更改为: if(choice=='4' || choice=='1' || choice=='3' || choice=='2')

关于c - 为什么从文件读取并打印到屏幕不起作用? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41397580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com