繁体   English   中英

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

[英]Is it correct to use a do-while loop inside a for loop? Why and why not?

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

5.2.4.1 Translation limits 中规定的,C 中允许嵌套各种复合语句,例如fordo / while至少最多 127 个级别。

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

  • 您的do / while循环在恒定条件下迭代,因为isent均未在正文或循环条件中进行修改,如果sent[i]是空格,则会导致无限循环。

  • 计算空格不是计算字符串中单词的正确方法: ""0单词,不是每个你想要的代码1个, " "也是,但你会得到2"AB"只有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循环可以解决给定的问题,再想一想, for循环可能是一种更安全的方法。 唯一需要do / while循环的地方是在宏扩展中,您希望将多个语句组合成一个复合语句:

#define swap_ints(a, b)  do { a ^= b; b ^= a; a ^= b; } while (0)

但是请注意,此宏中的交换方法效率低下,并且宏非常容易出错,比do / while循环更应该避免:)

for循环中嵌套do-while循环是完全有效的。 从语法上讲,您的程序没有任何问题。

但是,正如其他人所描述的,当sent[i] == ' '时,您的嵌套循环永远不会终止。 你的程序有错误,但它们与嵌套循环的有效性无关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM