首页 > 解决方案 > 使用do-while循环计算字符串中的字符、单词和行| C++

问题描述

我正在尝试将一个while对字符串中的字符、单词和行进行计数的循环转换为一个do-while循环。

这是我的while循环:

#include <stdio.h>
#include <string>
#include <typeinfo>
using namespace std;

int main()
{
    int c;
    int characters = 0;
    int words = 1;
    int newlines = 0;
    printf("Input a string.  Press enter, then ctrl+Z, then enter once more to end string.\n");

    while ((c = getchar()) != EOF)
    {
        if (c >= 'a' && c <= 'z' || c>= 'A' && c<= 'Z')
            characters++;
        else if (c == ' ')
            words++;
        else if (c == '\n')
            newlines++;
    }

    printf("The number of characters is %d\n", characters);
    printf("The number of words is %d\n", words);
    printf("The number of newlines is %d\n", newlines);


    return 0;
}

我已经尝试了几个小时使用do-while循环重复上述过程,但无济于事。

这是我到目前为止所拥有的:

#include <stdio.h>
#include <string>
#include <typeinfo>
using namespace std;  

int main()
{
    int c;
    int characters = 0;
    int words = 0;
    int newlines = 0;
    printf("Input a string.  Press enter, then ctrl+Z, then enter once more to end string.\n");
    
    do 
    {
        c = getchar();
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
            characters++;
        else if (c == ' ')
            words++;
        else if (c == '\n')
            newlines++;
    } while (c = getchar() != EOF);
        

    printf("The number of characters is %d\n", characters);
    printf("The number of words is %d\n", words);
    printf("The number of newlines is %d\n", newlines);

    return 0;
}

标签: c++visual-c++

解决方案


张贴循环有两个主要问题dowhile

第一个是您正在读取两个字符,但在循环的每次迭代中只处理字符。

第二个是它while (c = getchar() != EOF)没有做你希望它会做的事情。由于运算符优先级,这相当于 while (c = (getchar() != EOF)).

do 
{
    c = getchar(); // OK the first time, not after that.
    if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
        characters++;
    else if (c == ' ')
        words++;
    else if (c == '\n')
        newlines++;
} while (c = getchar() != EOF); // This is bad.

即使您通过使用解决第二个问题

while ((c = getchar()) != EOF);

它仍然不好,因为该行有利于检测 EOF,但字符被忽略以进行进一步处理。


您必须将do-while循环更改为:

do 
{
    c = getchar();
    if ( c == EOF )
    {
        break;
    }

    if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
        characters++;
    else if (c == ' ')
        words++;
    else if (c == '\n')
        newlines++;
} while (true);

如您所见,这并不是对while循环的改进。while从清洁度的角度来看,它比循环更糟糕。


推荐阅读