练习1 连续读入多个单词,然后统计这些单词的总的长度、以及单词个数

题目

连续读入多个单词,然后统计这些单词的总的长度、以及单词个数。
直到输入结束:
(按下Ctrl +z, 就会输入一个特殊的字符:文件结束符EOF)

c语言版本

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <Windows.h>

// 连续读入多个单词,然后统计这些单词的总的长度、以及单词个数。直到输入结束:
int main()
{
    char word[128];
    int count = 0;
    int length = 0;

    while (1)
    {
        // c语言要按3次 ctrl+z来退出循环
        if (scanf("%s", word) == EOF)
        {
            break;
        }
        count++;
        length += strlen(word);
    }

    printf("单词的个数:%d\n", count);
    printf("单词的长度:%d\n", length);
    printf("word: %s\n", word);  // 这里输出的是最后一个单词
    system("pause");
    return 0;
}

image

c++版本

#include <iostream>
#include <Windows.h>
#include <string>

using namespace std;

// 连续读入多个单词,然后统计这些单词的总的长度、以及单词个数。直到输入结束:

int main()
{
    string word; // 单词
    int length = 0; // 单词总长度
    int count = 0;  // 单词个数

    cout << "请输入任意个数单词:" << endl;
    while (1)
    {
        // 在控制台输入时,要借助ctrl+z(文件结束符)来结束循环
        if (!(cin >> word))  // 等价于(cin >> word) == 0,但是在vs中,cin>>的返回值不能直接和0进行比较
        {
            break;
        }
        length += word.length();
        count++;
    }

    cout << "单词的总长度是:" << length << endl;
    cout << "单词的个数是:" << count << endl;
    cout << "word:" << word << endl;

    system("pause");
    return 0;
}

image

posted @ 2022-04-05 12:51  荒年、  阅读(39)  评论(0编辑  收藏  举报