【发布时间】:2014-02-26 02:15:27
【问题描述】:
作为课程的一部分,我必须使用 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();
}
它确实有效(至少计算字符和单词的数量)。但是,当我编译代码并在控制台窗口上检查它时,我无法让程序停止运行。它应该在我输入回车键后立即结束。这是为什么呢?
【问题讨论】:
-
想想问题的本质。您编写了一个三重嵌套循环,其中问题似乎需要一个循环。尝试仅使用一个循环和一些 if 语句(或 switch)来对不同类型的字符执行不同的操作。
-
就是这样。我知道(或至少认为我知道)如何使用 if 语句(或 switch)来做到这一点,但老师不希望我们使用它。只有当..
-
附注:最后应该是
int main和return 0。 -
您确定您的老师说不要使用条件句吗?从您的帖子中可以看出他不希望您使用函数。两个不同的东西,if else 不是函数
-
在 if 语句之前会教你 while 循环,这似乎很奇怪。
标签: c while-loop char words text-segmentation