练习2 连续输入多行字符串(文本),统计中的行数,以及字符个数

题目

连续输入多行字符串(文本),统计中的行数,以及字符个数。

c++版本

  • c++用getline()获取一行
#include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

// 连续输入多行字符串(文本),统计中的行数,以及字符个数。
int main()
{
    string line;
    int lineCount = 0;
    int length = 0;

    cout << "请输入任意多行: " << endl;

    while (1)
    {
        //getline(cin, line);
        if (!(getline(cin, line)))
        {
            break;
        }
        lineCount++;
        length += line.length();
    }

    cout << "总行数: " << lineCount << endl;
    cout << "字符个数:" << length << endl;

    system("pause");
    return 0;
}

image

c版本

  • c语言用gets()获取一行;
#include <stdio.h>
#include <Windows.h>
#include <string.h>

int main()
{
    char line[2048];
    int lineCount = 0;
    int length = 0;

    printf("请输入任意行:\n");

    while (1)
    {
        if (!(gets_s(line, 2048)))
        {
            break;
        }
        lineCount++;
        length += strlen(line);
    }

    printf("总行数:%d\n", lineCount);
    printf("字符数:%d\n", length);

    system("pause");
    return 0;
}

image

posted @ 2022-04-05 14:52  荒年、  阅读(203)  评论(0编辑  收藏  举报