[进阶]C++:语句

2019-03-23  本文已影响0人  离群土拨鼠

常见的语句for,if,else,while都熟了。写一些用的不熟的。

switch语句

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
    char ch;
    while (cin >> ch)
    {
        switch (ch)
        {
        case 'a':
            ++aCnt;
            break;
        case 'e':
            ++eCnt;
            break;
        case 'i':
            ++iCnt;
            break;
        case 'o':
            ++oCnt;
            break;
        case 'u':
            ++uCnt;
            break;
        default:
            break;
        }
    }
    system("pause");
    return 0;
}
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
    char ch;
    while (cin >> ch)
    {
        switch (ch)
        {
            case 'a':   
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                ++uCnt;
                break;
        
        }
    }
    system("pause");
    return 0;
}

如果没有一个case标签能和switch匹配,程序将执行紧跟在default标签后面的语句。

范围for语句

for (declaration:expression)
statement

vector<int> v={0,1,2,3,4,5,6,7,8,9};
for(auto &r:v)
    r*=2;

你会发现引用不是只能绑定一次吗,为什么可以便利所用呢?其实是下面的等价。

for (auto beg = v.begin(), end = v.end(); beg != end; ++beg)
    {
        auto &r = *beg;
        r *= 2;
    }

continue语句

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string buf;
    while (std::cin >> buf && !buf.empty())
    {
        if (buf[0] != '_')
        {
            continue;//接着读入下一个输入
        }
        std::cout << "Hello World!\n";//程序执行到了这里说明输入的是以下划线开始的
    }
   
    

}

goto语句

goto语句的语法形式

goto label;
其中,label是用于标识一条语句的标识符:end : return;

try语句块和异常处理

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string buf;
    int a = 0;
begin:
    a = 10;
    while (std::cin >> buf && !buf.empty())
    {
        std::cout << a++ << endl;
        try
        {
            if (buf[0] != '_')
            {
                continue;//接着读入下一个输入
            }
            if (buf[0] != 'A')
            {
                throw runtime_error("A is not number!");
            }

    
        }
        catch (runtime_error err)
        {
            std::cout << err.what()
                << "Agaiin? y or n" << endl;
            char c;
            cin >> c;
            if (!cin || c == 'n')
                break;
            else
            {
                goto begin;
            }
        }
        
    }
   
    

}

参考:C++primer 第五版

上一篇 下一篇

猜你喜欢

热点阅读