C++Primer 第五章 语句

本文介绍了C++编程中关于语句的一些关键知识点,包括空语句的使用、复合语句、switch-case的编写原则以及避免在循环中的常见错误。此外,针对习题5.14,讲解了如何编写程序来查找标准输入中的重复单词,以发现连续出现的单词并记录最大重复次数。
摘要由CSDN通过智能技术生成

知识点:

1.使用空语句应加注释,让别人知道有意义。多余的空语句并非总是无害的。

2.快(block)即复合语句(compound statement), 块不以分号结束。

3.一般不省略case分支最后的break语句,如果没写,最好加注释说明。

4.最好不省略defualt标签。

5.不确定迭代多少次,用while循环比较合适

6.将一个整数读入vector用for实现:

vector <int> v;
for (int i ;cin>>i;)
  v.push_back(i);
7, c++11新标准: 范围for语句(range for statement)

8. continue 语句 只能出现在 for,while, do while 循环的内部。switch要在迭代语句内部时才能在switch中用continue。


习题:

Exercise 5.14

Write a program to read strings from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated. For example, if the input is

how now now now brown cow cow

the output should indicate that the word now occurred three times.

#include <iostream>
#include <string>

using std::cout; using std::cin; using std::endl; using std::string; using std::pair;

int main()
{ 
    pair<string, int> max_duplicated;
    int count = 0;
    for (string str, prestr; cin >> str; prestr = str)
    {
        if (str == prestr) ++count;
        else count = 0; 
        if (count > max_duplicated.second) max_duplicated = { prestr, count };
    }
    
    if (max_duplicated.first.empty()) cout << "There's no duplicated string." << endl;
    else cout << "the word " << max_duplicated.first << " occurred " << max_duplicated.second + 1 << " times. " << endl;
    
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值