sách gpt4 ăn đã đi

c - 退出 Do While 循环

In lại Tác giả: Walker 123 更新时间:2023-11-30 20:19:39 33 4
mua khóa gpt4 giày 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 
#include
#include
#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
for(int j=0; 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
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
if(max<>
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
if(strlen(stringArray[i])==j){
value++;
}
}
printf("| %d || %d | \n",j,value);
value=0;
}
printf("\n****************************************\n");
}

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

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

câu trả lời hay nhất

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

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

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

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

33 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress