[C++ primer]第五章笔记-语句

语句
练习5.9、编写一段程序,使用一系列if语句统计从cin读入文本中有多少元音字母。
<pre name="code" class="cpp">int main(){
	string str;
	int num=0;
	while (cin >> str){
		for (auto i : str){
			if (i == 'a')
				num++;
			if (i == 'e')
				num++;
			if (i == 'i')
				num++;
			if (i == 'o')
				num++;
			if (i == 'u')
				num++;
		}
		cout << "共有" << num << "个原音字母" << endl;
		system("pause");
	}
}

 练习5.10 
在for循环中加上(i=tolower(i);)即可。

练习5.11、5.12,修改统计元音字母程序,使其也能统计空格、制表符、和换行符,fi,fl,ff。
#include<iostream>
#include<string>
using namespace std;

int main(){
	string str;
	int num = 0,space_num=0,zhibiao_num=0,enter_num=0,ff_num=0,fi_num=0,fl_num=0;
	while (getline(cin,str)){
		for (int i = 0; i != str.size();++i){
			//i=tolower(i);5.10
			if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||str[i] == 'o' || str[i] == 'u')
				num++;
			if (str[i] == ' ')
				space_num++;
			if (str[i] == '\\'){
				if (str[i+1]=='t')
				zhibiao_num++;
				if (str[i+1] == 'n')
				enter_num++;
			}
			if (str[i] == 'f'){
				if (str[i + 1] == 'f')
				{
					ff_num++;
					++i;
				}
				if (str[i + 1] == 'i')
				{
					fi_num++;
					++i;
				}
				if (str[i + 1] == 'l')
				{
					fl_num++;
					++i;
				}

			}
		}
		cout << "共有" << num << "个原音字母" << endl;
		cout  << space_num << "个空格" << endl;
		cout << zhibiao_num << "个制表符" << endl;
		cout  << enter_num << "个换行符" << endl;
		cout << ff_num << "个ff" << endl;
		cout << fl_num << "个fi" << endl;
		cout << fi_num << "个fl" << endl;
		system("pause");
	}
}
用cin是不会保存空格,由于改用getline。

练习5.14
#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main(){

	string str,max_str;
	vector<string>ivec;
	int max_num = 0;
	while (cin>>str)
		ivec.push_back(str);
	int temp_num = 1;
	for (int i = 0; i != ivec.size()-1;++i){
		string temp_str = ivec[i];	
		if (ivec[i + 1] == ivec[i]){
			temp_num++;
			if (temp_num > max_num)
			{
				max_str = ivec[i];
				max_num = temp_num;
			}
		}
		else
			temp_num = 1;
		
	}
	cout << "单词" << max_str << "出现了" << max_num << "次!" << endl;
	system("pause");
}

跳转语句
1、break语句
break语句负责终止离他最近的while、do-while、for、switch语句。
2、continue语句
continue语句终止最近的循环当中的当前迭代并立即开始下一次迭代。
3、goto语句
goto语句作用是从goto语句无条件跳转到同意函数另一条语句。
练习5.20
#include<iostream>
#include<string>
using namespace std;

int main(){
	string str;
	string temp_str ="";
	while (cin >> str){
		if (str == temp_str){
		cout << "重复出现的单词是" << temp_str << endl;
		break;
	}
		else
		temp_str = str;
	}
	cout << "没有出现连续重复单词" <<endl;
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值