gpt4 book ai didi

计算c中一个段落中的句子数

转载 作者:行者123 更新时间:2023-12-04 09:38:13 24 4
gpt4 key购买 nike

作为类(class)的一部分,我必须使用 Turbo C 来学习 C(不幸的是)。

我们的老师让我们做一段代码来统计一个段落中的字符、单词和句子的数量(只使用 printf、getch() 和一个 while 循环..他不希望我们使用任何其他命令)。这是我写的代码:

#include <stdio.h>
#include <conio.h>

void main(void)
{
clrscr();
int count = 0;
int words = 0;
int sentences = 0;
char ch;

while ((ch = getch()) != '\n')
{
printf("%c", ch);
while ((ch = getch()) != '.')
{
printf("%c", ch);
while ((ch = getch()) != ' ')
{
printf("%c", ch);
count++;
}
printf("%c", ch);
words++;
}
sentences++;
}

printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}

它确实有效(至少计算字符和单词的数量)。但是,当我编译代码并在控制台窗口中检查它时,我无法让程序停止运行。它应该在我输入回车键后立即结束。这是为什么?

最佳答案

这里是您的问题的解决方案:

#include <stdio.h>
#include <conio.h>

void main(void)
{
clrscr();
int count = 0;
int words = 0;
int sentences = 0;
char ch;

ch = getch();
while (ch != '\n')
{
while (ch != '.' && ch != '\n')
{
while (ch != ' ' && ch != '\n' && ch != '.')
{
count++;
ch = getch();
printf("%c", ch);
}
words++;
while(ch == ' ') {
ch = getch();
printf("%c", ch);
}
}
sentences++;
while(ch == '.' && ch == ' ') {
ch = getch();
printf("%c", ch);
}
}

printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}

您的代码的问题是最里面的 while 循环消耗了所有字符。每当您进入那里并键入一个点或一个换行符时,它都会停留在该循环内,因为 ch 不同于空白。但是,当您退出最内层的循环时,您有可能会卡在第二个循环中,因为 ch 将是一个空白,因此总是与 '.' 不同。和'\n'。因为在我的解决方案中你只在最里面的循环中获取一个字符,所以在其他循环中你需要“吃掉”空白和点才能继续其他字符。

在两个内部循环中检查这些条件可以使代码正常工作。请注意,我删除了您的一些指纹。

希望对您有所帮助。

编辑:我在 sentences++ 之后的 while 循环中添加了打印您键入内容的说明和最后一次检查以检查空格,否则它会多计算一个单词。

关于计算c中一个段落中的句子数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21513043/

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