gpt4 book ai didi

c - 退出 Do While 循环

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

我正在做一些作业,遇到了这个问题。

Write a program that reads several lines of text and prints a table indicating the number of one-letter words, two-letter words,three-letter words, and so on, appearing in the text. For example thephrase "Whether 'tis nobler in the mind to suffer"

Will contain

1 letter words: 0

2 letter words: 2

3 letter words: 1

4 letter words: 2 (including 'tis)

5 letter words: 0

6 letter words: 2

7 letter words: 1

我的问题代码如下。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXDIMENSIONS 1000 //set max dimensions
#define MAXLENGTH 1000 //set max length

void separate(char stringArray[][MAXLENGTH], int words);
void printTable(char stringArray[][MAXLENGTH], int c);

int main(int argc, char** argv) {

char txt[MAXLENGTH];
char *token;
char mat[MAXDIMENSIONS][MAXLENGTH];
int i=0,wordcount=0;

do{
printf(">>>Write and press enter (EXIT for end of program)<<< : ",49);
fgets(txt,sizeof txt,stdin);
if(strcmp(txt,"EXIT")!=0)
{
token=strtok(txt," ");
strcpy(mat[i],token);
i++;
while(token!=NULL){
token=strtok(NULL, " ");
if(token!=NULL){
strcpy(mat[i],token);
i++;
}
}
}
}while(strcmp(txt,"EXIT")!=0);

separate(mat,i);

printTable(mat,i);

return (EXIT_SUCCESS);
} // end of main

void separate(char stringArray[][MAXLENGTH], int words){
for(int i=0; i<words; i++){
for(int j=0; j<strlen(stringArray[i]); j++){
if((stringArray[i][j]<65 && stringArray[i][j]!=39) || (stringArray[i][j]>90 && stringArray[i][j]<97)|| stringArray[i][j]>122){
for(int g=j; g<strlen(stringArray[i]); g++){
stringArray[i][g]=stringArray[i][g+1];
}
}
}
}
}

void printTable(char stringArray[][MAXLENGTH], int c){
int max;
int value=0,j;

max=strlen(stringArray[0]);
for(int i=1; i<c; i++){
if(max<strlen(stringArray[i])){
max=strlen(stringArray[i]);
}
}

printf("\n***********WORD LENGTH READER***********\n");
printf("| LENGTHS || VALUES | \n");
for(j=1; j<=max; j++){
for(int i=0; i<c; i++){
if(strlen(stringArray[i])==j){
value++;
}
}
printf("| %d || %d | \n",j,value);
value=0;
}
printf("\n****************************************\n");
}

我的问题是跳出第 17-33 行的 do while 循环。这是我第一次使用 fgets,我相信这可能是导致问题的原因。我使用 gets 编写了代码,它的工作原理与此类似,但我知道由于其漏洞,不应使用 gets。

感谢任何帮助。提前致谢!

最佳答案

因为 fgets 也会读取换行符,因此您的退出条件将不会因为换行符而得到满足。您可以在检查中包含换行符,"EXIT\n",也可以在 fgets 之后修补换行符。

下面的示例也使循环变得更简单:

do {
fgets(txt,sizeof txt,stdin);
char *p= strrchr(txt,'\n'); if (p) *p= '\0';
if(strcmp(txt,"EXIT")==0)
break;
//....
while(1);

关于c - 退出 Do While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435384/

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