连续读入多个单词,然后统计这些单词的总的长度、以及单词个数。
直到输入结束:
(按下
Ctrl +z,
就会输入一个特殊的字符:文件结束符
EOF
)
#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;
int main()
{
string word;
int count=0;
int length = 0;
cout << "请输入任意多个单词: " << endl;
while (1)//按下ctrl+z,就会产生一个特殊字符"EOF"(文件结束符);
{
//当遇到"EOF"文件结束符时,返回空0(NULL);
if (!(cin >> word))//cin 返回的是一个对象,高版本不能和0去比较
{
break;//跳出循环
}
count++;
length += word.length();
}
cout << "一共有" << count << "个单词" << endl;
cout << "总长度为:" << length << endl;
return 0;
}
运行结果:
连续输入多行字符串(文本),统计中的行数,以及字符个数。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string line;
int countline=0;
int strnum=0;
cout << "请输入任意行: " << endl;
while (1)
{
if (!getline(cin, line))
{
break;
}
countline++;
strnum += line.length();
}
cout << "行数为: " << countline << endl;
cout << "字符串总长度为" << strnum << endl;
system("pause");
return 0;
}
运行结果