c - 在 for 循环中使用 do-while 循环是否正确?为什么以及为什么不呢?

标签 c for-loop do-while

//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 循环。或者如果可以的话,该怎么做。

最佳答案

嵌套各种复合语句,例如fordo/while C 中允许的级别至少为 127 个级别,如5.2.4.1 翻译限制中指定。

问题不是语法问题,而是概念问题:

  • 您的do/while循环在恒定条件下迭代 i ,也不是sent在主体或循环条件中被修改,导致无限循环 if sent[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/

相关文章:

c - 将 C 代码移植到 ActionScript 2

javascript - Javascript 中 for 循环内的 setInterval

java - 我如何在 Java 中将一个数字重复乘以 2 直到它达到 100 万?

java - 使用 while 循环或任何其他方法只接受正整数

c - 使用通用函数将整数与短整数交换

c - C中结构中的动态结构数组

java - Play框架,for循环内的动态语句

r - 使用 for 循环生成 ggplots 网格

php - 为什么 echo 在 do while 循环中甚至在 ignore_user_abort(1) 时都不起作用?

c++ - 限制 WINAPI 中的调整大小方向