//program to count words
#include<stdio.h>
int main()
{
int i;
int word = 0;
char sent[] = "How are you doing mister"; //character pointer
for (i = 0; sent[i] != '\0'; i++)
{
do
{
word++;
} while (sent[i] == ' ');
}
printf("There are %d words in the sentence\n", word + 1); //words are always 1 more than the no. of spaces.
return 0; //or word=1;
}
这是一个用于计算字数的代码。请告诉我为什么我们不能在 for 循环中使用 do-while 循环。或者如果可以的话,该怎么做。
最佳答案
嵌套各种复合语句,例如for
和do
/while
C 中允许的级别至少为 127 个级别,如5.2.4.1 翻译限制中指定。
问题不是语法问题,而是概念问题:
您的
do
/while
循环在恒定条件下迭代i
,也不是sent
在主体或循环条件中被修改,导致无限循环 ifsent[i]
是一个空格。计算空格数并不是计算字符串中单词数的正确方法:
""
有0
言语,不是1
根据您想要的代码," "
但你会得到2
和"A B"
只有2
言语,不是3
.您应该计算从空格到非空格的转换次数,从字符串开头之前的隐式空格开始。
另请注意
char sent[] = "...";
不是字符指针,而是字符数组。
这是修改后的版本:
//program to count words
#include <stdio.h>
int main() {
int i, words, last;
char sent[] = "How are you doing mister?";
words = 0;
last = ' ';
for (i = 0; sent[i] != '\0'; i++) {
if (sent[i] != ' ' && last == ' ')
word++;
last = sent[i];
}
printf("There are %d words in the sentence '%s'\n", words, sent);
return 0;
}
根据我校对代码的经验,do
/while
循环往往会被错误地编写,尤其是初学者,缺少测试条件或以其他方式损坏。我你认为do
/while
循环解决了给定的问题,再想一想,a for
循环可能是一种更安全的方法。唯一的地方do
/while
在宏扩展中需要循环,您希望将多个语句组合成单个复合语句:
#define swap_ints(a, b) do { a ^= b; b ^= a; a ^= b; } while (0)
但请注意,此宏中的交换方法效率低下,并且宏非常容易出错,应该避免超过do
。/while
循环:)
关于c - 在 for 循环中使用 do-while 循环是否正确?为什么以及为什么不呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56783231/