C++ primer review (four, statement)

5.1, simple sentences

  • Empty statement: ';'does nothing, but it is indeed a statement
  • Conforming statement: Many statements are recommended to be enclosed in curly braces
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    
     for(int i = 1;i < 10;i ++) ;//糟糕误入一个空语句,循环了空语句
   cout<<"进行"<<endl;
   for(int j = 1;j < 10;j++)
   {
    
    
       cout<<j<<endl;
   }
    system("pause");
    return 0;
}

5.2, conditional statement

1、if-else if-else语句

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
    
       string a = "我爱你";
    if(a ==  "我爱你") cout<<"是爱你的"<<endl;
    else if(a == "我不爱你") cout<<"我喜欢其他人"<<endl;
    else cout<<"我喜欢学习"<<endl;
    system("pause");
    return 0;
}

2, swithch statement

#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    
       char a;
cout<<"请输入一个字母"<<endl;
cin>>a;
    switch(a){
    
    
        case 'a':
        case 'e':
        case 'o':
        case 'i':
        case 'u':
        cout<<"是元音字母"<<endl;
        break;
        default:
        cout<<"不是元音字母"<<endl;
        break;
    }
    system("pause");
    return 0;
}

5.3, iterative statement

  • while statement
  • Traditional for statement
  • Range for statement
  • do while statement
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    
       char a;
    int b;
    string c = "1234567";
    cout<<"如果用传统while,输入1;如果用for语句,输入2;如果用范围for语句,输入3;如果输入do while语句,输入4"<<endl;
    cin>>b;
    if(b == 1){
    
    
    cout<<"请任意输入:";
    while(cin>>a){
    
    
        cout<<a<<endl;
    }
    }
    else if(b == 2){
    
    
        for(int i = 0;i < 10;i++){
    
    
            cout<<i<<endl;
        }
    }
    else if(b == 3){
    
    
        for(auto ci:c) cout<<ci<<endl;
    }
    else if(b == 4){
    
    
        int d = 1;
        do{
    
    
            cout<<d<<endl;
        }while(d < 9);
    }
    else cout<<"重新输出"<<endl;
    system("pause");
    return 0;
}

5.4, ​​jump statement

  • break statement
  • continue statement
  • goto statement, not recommended
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    
       
    int i = 0;
    while(i > -1){
    
    
        i++;
        if(i == 9) continue;
        if(i == 20) break;
        cout<<i<<endl;
    }
    system("pause");
    return 0;
}

5.5, try statement block and exception handling

#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    
       string a;
    cout<<"请输入Yes或No"<<endl;
    cin>>a;
    try{
    
    
    if(a == "Yes" || a == "No") cout<<"输入正常"<<endl;
    else logic_error("is a error");
    }
    catch(logic_error l){
    
    
        cout<<l.what()<<"What "<<endl;
    }
    system("pause");
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45743162/article/details/115263303