第 5 章 语句

练习

练习5.4:

// iter指向nullptr,无效。
while (string::iterator iter != s.end()) { /* . . . */ }
// 正确:
string::iterator iter = s.begin();
while (iter != s.end()) { /* . . . */ }

// if语句不在while语句块中,所以status是无效的。
while (bool status = find(word)) { /* . . . */ }
    if (!status) { /* . . . */ }
// 正确:
bool status;
while ((status = find(word))) {/* ... */}
if (!status) {/* ... */}

练习5.5:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main()
{
	const vector<string> scores = { "F", "D", "C", "B", "A", "A+" };
	unsigned grade = 0;
	string lettergrade;
	cout << "please input your grade:" << endl;
	while (cin >> grade)
	{
		if (grade < 60)
			lettergrade = scores[0];
		else
			lettergrade = scores[(grade - 50) / 10];
        cout << lettergrade << endl;
	}
	return 0;
}

练习5.6:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main()
{
	const vector<string> scores = { "F", "D", "C", "B", "A", "A+" };
	unsigned grade = 0;
	string lettergrade;
	cout << "please input your grade:" << endl;
	while (cin >> grade)
	{
		lettergrade = (grade < 60) ? scores[0] : scores[(grade - 50) / 10];
        cout << lettergrade << endl;
	}
	return 0;
}

练习5.7:

// (a)
if (ival1 != ival2) 
    ival1 = ival2;
else ival1 = ival2 = 0;
// (b)
if (ival < minval)
{
    minval = ival;
    occurs = 1;
}
// (c)
int val;
if (ival = get_value())
    cout << "ival = " << ival << endl;
if (!ival)
    cout << "ival = 0\n";
// (c)
if (ival == 0)
    ival = get_value();

练习5.8:

        在c++中,else总是与前面最近的不匹配if配对。

练习5.9:

#include<iostream>
using namespace std;

int main()
{
	unsigned vowelCnt = 0;
	char c;
	while (cin >> c)
	{
		if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
			++vowelCnt;
	}
	cout << "Number of vowel are " << vowelCnt << endl;

    return 0;
}

练习5.10:

#include<iostream>
using namespace std;

int main()
{
    unsigned vowelCnt = 0, aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, 
        otherCnt = 0;
    char ch;
    while (cin >> ch)
    {
    	switch (ch)
    	{
    	case 'a': case 'A':
    		++aCnt;
    		break;
    	case 'e': case 'E':
    		++eCnt;
    		break;
    	case 'i': case 'I':
    		++iCnt;
    		break;
    	case 'o': case 'O':
    		++oCnt;
    		break;
    	case 'u': case 'U':
    		++uCnt;
    		break;
    	default:
    		++otherCnt;	
    		break;
    	}
    }
    vowelCnt = aCnt + eCnt + iCnt + oCnt + uCnt;
    cout << "vowelCnt   = \t" << vowelCnt << endl;
    cout << "    aCnt   = \t" << aCnt << endl;
    cout << "    eCnt   = \t" << eCnt << endl;
    cout << "    iCnt   = \t" << iCnt << endl;
    cout << "    oCnt   = \t" << oCnt << endl;
    cout << "    uCnt   = \t" << uCnt << endl;
    cout << "otherCnt   = \t" << otherCnt << endl;

    return 0;
}

练习5.11:

#include<iostream>
using namespace std;

int main()
{
    unsigned vowelCnt = 0, aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, 
        spaceCnt = 0, tableCnt = 0, newlineCnt = 0, otherCnt = 0;
    char ch;
    // cin 会过滤掉不可见字符(如 空格 回车,TAB 等)
    //不想略过空白字符,那就使用 noskipws 流控制 或 cin.get(ch)
    while (cin >> noskipws >> ch) 
    {
    	switch (ch)
    	{
    	case 'a': case 'A':
    		++aCnt;
    		break;
    	case 'e': case 'E':
    		++eCnt;
    		break;
    	case 'i': case 'I':
    		++iCnt;
    		break;
    	case 'o': case 'O':
    		++oCnt;
    		break;
    	case 'u': case 'U':
    		++uCnt;
    		break;
    	case ' ':
    		++spaceCnt;
    		break;
    	case '\t':
    		++tableCnt;
    		break;
    	case '\n':
    		++newlineCnt;
    		break;
    	default:
    		++otherCnt;
    		break;
    	}
    }
    vowelCnt = aCnt + eCnt + iCnt + oCnt + uCnt;
    cout << "vowelCnt   = \t" << vowelCnt << endl;
    cout << "    aCnt   = \t" << aCnt << endl;
    cout << "    eCnt   = \t" << eCnt << endl;
    cout << "    iCnt   = \t" << iCnt << endl;
    cout << "    oCnt   = \t" << oCnt << endl;
    cout << "    uCnt   = \t" << uCnt << endl;
    cout << "spaceCnt   = \t" << spaceCnt << endl;
    cout << "tableCnt   = \t" << tableCnt << endl;
    cout << "newlineCnt = \t" << newlineCnt << endl;
    cout << "otherCnt   = \t" << otherCnt << endl;

    return 0;
}

练习5.12:

#include<iostream>
using namespace std;

int main()
{
    char cur_char, bef_char = '\0';
 	unsigned vowelCnt = 0, aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
 	unsigned spaceCnt = 0, tableCnt = 0, newlineCnt = 0;
 	unsigned ffCnt = 0, flCnt = 0, fiCnt = 0;
 	while (cin.get(cur_char))
 	{
 		switch (cur_char)
 		{
 		case 'a': case 'A':
 			++aCnt;
 			break;
 		case 'e': case 'E':
 			++eCnt;
 			break;
 		case 'i':
 			if (bef_char == 'f')
 			{
 				++fiCnt;
 			}
 		case 'I':
 			++iCnt;
 			break;
 		case 'o': case 'O':
 			++oCnt;
 			break;
 		case 'u': case 'U':
 			++uCnt;
 			break;
 		case ' ':
 			++spaceCnt;
 			break;
 		case '\t':
 			++tableCnt;
 			break;
 		case '\n':
 			++newlineCnt;
 			break;
 		case 'f':
 			if (bef_char == 'f')
 			{
 				++ffCnt;
 			}
 			break;
 		case 'l':
 			if (bef_char == 'f')
 			{
 				++flCnt;
 			}
 			break;
 		default:
 			break;
 		}
 		bef_char = cur_char;  //将当前的字符赋给bef_char,作为下次判断的依据
 	}
 	vowelCnt = aCnt + eCnt + iCnt + oCnt + uCnt;
 	cout << "vowelCnt   = \t" << vowelCnt << endl;
 	cout << "    aCnt   = \t" << aCnt << endl;
 	cout << "    eCnt   = \t" << eCnt << endl;
 	cout << "    iCnt   = \t" << iCnt << endl;
 	cout << "    oCnt   = \t" << oCnt << endl;
 	cout << "    uCnt   = \t" << uCnt << endl;
 	cout << "   ffCnt   = \t" << ffCnt << endl;
 	cout << "   flCnt   = \t" << flCnt << endl;
 	cout << "   fiCnt   = \t" << fiCnt << endl;
 	cout << "spaceCnt   = \t" << spaceCnt << endl;
 	cout << "tableCnt   = \t" << tableCnt << endl;
 	cout << "newlineCnt = \t" << newlineCnt << endl;

    return 0;
}

练习5.13:

// (a) 应该有break语句
unsigned aCnt = 0, eCnt = 0, iouCnt = 0;
char ch = next_text();
switch (ch) {
case 'a': aCnt++; break;
case 'e': eCnt++; break;
default: iouCnt++; break;
}
// (b) ix应该在外部定义
unsigned index = some_value();
int ix;
switch (index) {
case 1:
    ix = get_value();
    ivec[ix] = index;
    break;
default:
    ix = static_cast<int>(ivec.size()) - 1;
    ivec[ix] = index;
}
// (c) case语法错误
unsigned evenCnt = 0, oddCnt = 0;
int digit = get_num() % 10;
switch (digit) {
case 1: case 3: case 5: case 7: case 9:
    oddcnt++;
    break;
case 2: case 4: case 6: case 8: case 0:
    evencnt++;
    break;
}
// (d) Case标签必须是常量表达式
const unsigned ival = 512, jval = 1024, kval = 4096;
unsigned bufsize;
unsigned swt = get_bufCnt();
switch (swt) {
case ival:
    bufsize = ival * sizeof(int);
    break;
case jval:
    bufsize = jval * sizeof(int);
    break;
case kval:
    bufsize = kval * sizeof(int);
    break;
}

练习5.14:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    // 初始化前一个单词,输入的当前单词,重复出现最大次数的单词
    string pre_word, cur_word, max_repeat_word;
    // 初始化重复出现次数,重复出现的最大次数
    int repeat_times = 0, max_repeat_times = 0;
    
    while (cin >> cur_word)
    {
        if (cur_word == pre_word)
            ++repeat_times;
        else
        {
            pre_word = cur_word;
            repeat_times = 0;
        }

        if (max_repeat_times < repeat_times)
        {
            max_repeat_times = repeat_times;
            max_repeat_word = cur_word;
        }
    }

    if (!max_repeat_times) 
        cout << "no word was repeated" << endl;
    else 
        cout << "the word '" << max_repeat_word << "' repeatedly occurred "
             << max_repeat_times << " times" << endl;

    return 0;
}

练习5.15:

// (a)
int ix;
for (ix = 0; ix != sz; ++ix) { /* ... */ }
if (ix != sz)
    // . . .
// (b)
int ix;
for (; ix != sz; ++ix) { /* ... */ }
// (c)
for (int ix = 0; ix != sz; ++ix) { /*...*/ }

练习5.16:

// while 常用
int i;
while ( cin >> i )
    // ...

// for改写
for (int i = 0; cin >> i;)
    // ...

// for 常用
for (int i = 0; i != size; ++i)
    // ...

// while改写
int i = 0;
while (i != size)
{
    // ...
    ++i;
}

练习5.17:

#include<iostream>
#include<vector>
using namespace std;

bool is_subVec(vector<int> vec1, vector<int> vec2)
{
    vector<int>::size_type min_size = vec1.size() < vec2.size() ? 
        vec1.size() : vec2.size();
    for (vector<int>::size_type i = 0; i != min_size; ++i)
    {
        if (vec1[i] != vec2[i])
            return false;
    }
    return true;
}

int main()
{
    vector<int> vec1{ 0, 1, 1, 2 };
    vector<int> vec2{ 0, 1, 1, 2, 3, 5, 8 };
    cout << is_subVec(vec1, vec2) << endl;

    return 0;
}

练习5.18:

// (a)
do {
    int v1, v2;
    cout << "Please enter two numbers to sum:";
    if (cin >> v1 >> v2)
        cout << "Sum is: " << v1 + v2 << endl;
} while (cin);
// (b)
int ival;
do {
    // . . .
} while (ival = get_response());
// (c)
int ival = get_response();
do {
    ival = get_response();
} while (ival);

练习5.19:

#include<iostream>
using namespace std;

int main()
{
    do
	{
		cout << "please input two string object:" << endl;
		string str1, str2;
		cin >> str1 >> str2;
		cout << "The shorter is " 
             << (str1.size() <= str2.size() ? str1 : str2) << endl;
	} while (cin);

    return 0;
}

练习5.20:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string cur_str, bef_str;
    bool repeate_twice = false;
    
    while (cin >> cur_str)
    {
        if (cur_str == bef_str)
        {
            cout << cur_str << " occurs twice in succession." << endl;
            repeate_twice = true;
            break;
        }
    	else
    		bef_str = cur_str;
    }

    if (!repeate_twice)
        cout << "no word was repeated." << endl;

    return 0;
}

练习5.21:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string cur_str, bef_str;
    bool repeate_twice = false;
    
    while (cin >> cur_str)
    {
        // 首字母不是大写退出当前迭代
        if (!isupper(cur_str[0]))
            continue;
        if (cur_str == bef_str)
        {
            cout << cur_str << " occurs twice in succession." << endl;
            repeate_twice = true;
            break;
        }
    	else
    		bef_str = cur_str;
    }

    if (!repeate_twice)
        cout << "no word was repeated." << endl;

    return 0;
}

练习5.22:

// 向后跳过已初始化的变量定义是可以的
begin:
    int sz = get_size();
    if (sz <= 0) {
        goto begin;
    }

for (int sz = get_size(); sz <=0; sz = get_size())

练习5.23:

#include<iostream>
using namespace std;

int main()
{
    int a, b;
    cout << "Enter two integers for division: " << endl;
    while (cin >> a >> b)
        cout << static_cast<double>(a) / b << endl;

    return 0;
}

练习5.24:

#include<iostream>
#include<stdexcept>
using namespace std;

int main()
{
    int a, b;
    cout << "Enter two integers for division: " << endl;
    while (cin >> a >> b)
    {
        if (b == 0)
            throw runtime_error("Integer division by zero.");
        cout << static_cast<double>(a) / b << endl;
        cout << "Enter two integers for division: " << endl;
    }
        
    return 0;
}

练习5.25:

#include<iostream>
#include<stdexcept>
using namespace std;

int main()
{
    int a, b;
    cout << "Enter two integers for division: " << endl;
    while (cin >> a >> b)
    {
        try
        {
            if (b == 0)
                throw runtime_error("Integer division by zero.");
            cout << static_cast<double>(a) / b << endl;
            cout << "Enter two integers for division: " << endl;
        }
        catch (runtime_error err)
        {
            cout << err.what() << endl
                << "Try Again? Enter y or n" << endl;
            char c;
            cin >> c;
            if (!cin || c == 'n')
                break;
        } 
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值