fqy131314

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

C++版本

#include <iostream>

#include <string>

#include <Windows.h>

using namespace std;

int main(void) {

       string word;

       int count = 0;

       int length = 0;

       cout << "请输入任意多个单词:";

       while (1) {

              // 输入成功时,返回cin对象本身

              // 遇到文件结束符(ctrl+z),而导致输入失败是,返回0

           // vs, cin>>的返回值,不能直接和0比较,可改为:

           // if (!(cin>>word))

              if ((cin >> word) == 0) {

                     break;

              }

              count++;

              length += word.length();

       }

       cout << "一共有" << count << "单词" << endl;

       cout << "总长度:" << length << endl;

       system("pause");

       return 0;

}

C语言版本

#include <stdio.h>

#include <string.h>

#include <Windows.h>

int main(void) {

       char word[64];

       int count = 0;

       int length = 0;

       printf("请输入任意多个单词:");

       while (1) {

              // 输入失败 返回0

              // 遇到文件结束符 (ctrl+z),返回-1(EOF)

              if (scanf("%s", word) == -1) {

                     break;

              }

              count++;         

              length += strlen(word);

       }

       printf("一共有%d个单词\n", count);

       printf("总长度:%d\n", length);

       system("pause");

       return 0;

}

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

分别使用C和C++实现。

C语言版本

#include <stdio.h>

#include <string.h>

#include <Windows.h>

int main(void) {

      char line[2048];

      int lineCount = 0;

      int length = 0;

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

      while (1) {

            if ( gets(line) == 0) {

                  break;

            }

            lineCount++;

            length += strlen(line);

      }

      printf("一共有%d行\n", lineCount);

      printf("总长度:%d\n", length);

      system("pause");

      return 0;

}

C++版本

#include <iostream>

#include <string>

#include <Windows.h>

using namespace std;

int main(void) {

      string line;

      int lineCount = 0;

      int length = 0;

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

      while (1) {

            // 遇到文件结束符时, 返回NULL(0)

            if (getline(cin, line) == 0) {

                  break;

            }

            lineCount++;

            length += line.length();

      }

      cout << "一共有" << lineCount << "行" << endl;

      cout << "总长度: " << length << endl;

      system("pause");

      return 0;

}

posted on 2022-10-13 16:16  会飞的鱼-blog  阅读(30)  评论(0)    收藏  举报  来源

导航