计算字符串的长度

连续读入多个单词,然后统计这些单词的总的长度、以及单词个数。
直到输入结束:
(按下 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;
}

 运行结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值