1. 程式人生 > >C++筆記之零碎點

C++筆記之零碎點

1,測試cin.ignore()的作用,用於去除緩衝區的殘留資料 

#include <iostream>

int main()
{
    char buff[20];
    char buff1[20];

    std::cin >> buff1;
    std::cin.ignore(7, '\n');       // 通常把獲取前n個字元寫的很大,去掉前一次輸入的‘\n’
    std::cin.getline(buff, 10);     // 只能獲取9個,存最末尾儲'\0'

    std::cout << buff << std::endl;

    return 0;
}

2.整形的佔用位數

#include <iostream>
#include <climits>

int main()
{
    using namespace std;

    int n_int = INT_MAX;
    short n_short = SHRT_MAX;
    long n_long = LONG_MAX;
    long long n_llong = LLONG_MAX;

    cout << "int      : " << sizeof n_int << "bytes." << endl;
    cout << "short    : " << sizeof n_short << "bytes." << endl;
    cout << "long     : " << sizeof n_long << "bytes." << endl;
    cout << "long long: " << sizeof n_llong << "bytes." << endl;
    cout << endl;

    cout << "Maximum values:" << endl;
    cout << "int      : " << n_int << endl;
    cout << "short    : " << n_short << endl;
    cout << "long     : " << n_long << endl;
    cout << "long long: " << n_llong << endl;
    
}

執行結果: 

int      : 4bytes.
short    : 2bytes.
long     : 8bytes.
long long: 8bytes.

Maximum values:
int      : 2147483647
short    : 32767
long     : 9223372036854775807
long long: 9223372036854775807

3,整形溢位 

4,cin的相關方法 - ignore,get,getline,peek,gcount,read 

#include <iostream>
#include <climits>
using namespace std;
int main()
{
    const int SIZE = 50;
    char buff[SIZE];

    cout << "請輸入一段文字:";
    cin.read(buff, 10);         //讀取輸入,阻塞計數,不忽略回車

    cout << "輸入的文字字元數為:" << cin.gcount() << endl;  //統計

    cout << "輸入的文字資訊是:";
    cout.write(buff, 19);       //讀取緩衝區資料,列印
    cout << endl;

    return 0;

}

執行結果: 

請輸入一段文字:yfu
67t
87y
輸入的文字字元數為:10
輸入的文字資訊是:yfu
67t
8

5,檔案複製

此處換行符會被過濾掉,所以逐行讀取,手動新增ENDL。

#include <iostream>
#include <climits>
#include <fstream>

using namespace std;
int main()
{
    ifstream in; //檔案輸入流類物件
    in.open("../test.txt", ios::binary); //用兩種方法來開啟檔案
    ofstream out("../test1.txt", ios::binary | ios::app); //檔案輸出流類物件

    if(!in){
        cerr << "開啟檔案失敗" << endl;
        return 0;
    }

//    char x;
//    while( in >> x){
//        if(x != '\n'){
//            cout << x;
//            out << x;
//        }
//        else{
//            cout << "遇到換行";
//            out << "-------********\n";
//        }

    in.seekg(ios::beg); //指標指向檔案頭

    for(string s; getline(in, s);){
        cout << s << endl;
        out << s << endl;
    }

    cout << endl;

    in.close();
    out.close();

    return 0;
}

6,輸入輸出,切換迴圈

#include <iostream>

int main()
{
    char answer;

    std::cout << "請問你畢業了嗎?[Y/N]" << std::endl;
    std::cin >> answer;

    switch(answer){
        case 'Y':
        case 'y':
            std::cout << "你畢業了!" << std::endl;
            break;

        case 'N':
        case 'n':
            std::cout << "你怎麼還沒有畢業!" << std::endl;
            break;

        default:
            std::cout << "輸入不符合要求!!!" << std::endl;
            break;
    }

    std::cin.ignore(100, '\n');

    std::cout << "輸入任何字元結束" << std::endl;
    std::cin.get();

}

如圖7所示,溫度轉換(我寫的第一個C ++程式)

#include <iostream>

int main()
{
    // 輸入選擇,確定公式
    char answer;
    std::cout << "請問待轉換的溫度單位序號:\n"
              << "1. 華氏度(℉) \n"
              << "2. 攝氏度(℃) " << std::endl;
    std::cin >> answer;

    // 輸入溫度值
    float temperature;
    std::cout << "請輸入當前溫度:" << std::endl;
    std::cin.ignore(100, '\n');
    std::cin  >> temperature;

    // 進行判斷,輸出結果
    float f2c(float num);
    float c2f(float num);
    float result = -1000;

    switch(answer){
        case '1':
            result = f2c(temperature);
            break;
        case '2':
            result = c2f(temperature);
            break;
        default:
                        std::cout << "輸入不符合要求!!!" << std::endl;
            break;
    }

    if(result != -1000){
        std::cout << result << std::endl;
    }
    else{
        std::cout << "輸入錯誤" << std::endl;
    }

}

float f2c(float num){
    // 攝氏度 = 【(華氏度 - 32) ÷ 1.8】℃
    float result;

    result = (num-32) ;
    result /= 1.8;

    return result;
}

float c2f(float num){
    // 華氏度 = (32 + 攝氏度 × 1.8)℉
    float result;

    num *= 1.8 ;
    result = num + 32;

    return result;
}

手癢寫一個蟒蛇的版本:

temper = input('請輸入溫度,形如【23.2 C】或者【23.2 F】')
temp_value, temp_type = temper.split(' ')

temp_value = float(temp_value)
temp_type = temp_type.upper()

print(temp_type, temp_value)
if (temp_type == 'C') :
    result = str(round(temp_value*1.8 + 32, 2)) + '℉'
elif(temp_type == 'F') :
    result = str(round((temp_value-32)/1.8, 2)) + '℃'
else:
    result = None
    print('輸入有誤')

print(result)

8.地址運算子和間接值運算子的使用

#include<iostream>
#include<string>
#include <limits>

int main()
{
    using namespace std;

    int updates = 6;
    int *p_updates = &updates;

    cout << "Values: updates = " << updates;
    cout << ", *p_updates = " << *p_updates << endl;

    cout << "Addresses: &updates = " << &updates;
    cout << ", &p_updates = " << p_updates << endl;
    
    return 0;
}

執行結果如下: 

Values: updates = 6, *p_updates = 6
Addresses: &updates = 0x7ffd2f82ce0c, &p_updates = 0x7ffd2f82ce0c

可見,對變數名對應地址取間接運算子,相當與獲得變數名對應值

9.陣列的指標地址

#include<iostream>
#include<string>
#include <limits>

int main()
{
    const unsigned short ITEMS = 5;

    int intArray[ITEMS] = {1, 2, 3, 4, 5};
    char charArray[ITEMS] = {'f', 'I', 'j', 'K', ';'};

    int *intPtr = intArray;
    char *charPtr = charArray;
    
    //顯示整形陣列的記憶體地址
    std::cout << "整型陣列輸出:" << '\n';
    for (int i = 0; i < ITEMS; i++) {
        std::cout << *intPtr << " at " << reinterpret_cast<unsigned long>(intPtr) << std::endl;
        intPtr++;
    }
    
    //顯示位元組型陣列的記憶體地址和指標對列印的影響
    std::cout << "字元型陣列輸出:" << '\n';
    for (int i = 0; i < ITEMS; i++) {
        std::cout << *charPtr << " at " << reinterpret_cast<unsigned long>(charPtr) << " - " << charPtr << std::endl;
        charPtr++;
    }
    
    //測試運算
    int *temp = intArray;
    std::cout << *temp+1<< std::endl;
    std::cout << *(temp+1) << std::endl;
    return 0;
};

9.字串指標,動態建立

#include <iostream>
#include <string>

using namespace std;

int main()
{
    const int num = 5;
    
    string temp;
    auto *plist  = new string [num];

    for (int i = 0; i<num; i++) {
        cout << "請輸入第" << i+1 << "個字元" << endl;
        cin >> temp;

        plist[i] = temp;
    }

    cout << plist->length() << endl; //4個位元組,64位系統

    for (int i = 0; i<num; i++) {
        cout << plist << " --- " <<  plist[0] << endl; //不是plist[i]
        plist ++;   //指標加法,指向下一個字元
    }
    
}

10.輸出階乘

#include <iostream>
#include <string>

using namespace std;

struct student{
    char age[20];
    char gender[20];
    string name;
};

const int Arsize = 16;

int main()
{
    long long factor[Arsize];
    factor[0] = factor[1] = 1LL;

    for (int i = 2; i<Arsize; i++) {
        factor[i] = factor[i-1] *i;
    }

    for (long long i : factor) {
        cout << i << "! = " << i << endl;
        
    }
}

 11. 列舉和switch的組合使用

#include <iostream>
#include <string>
#include <vector>

using namespace std;

enum {
    red, orange, yellow, green, blue, violet, indigo
};

int main() {
    cout << "請輸入你的選擇(0-6): \n";

    int code;

    while (cin >> code && code >= 0 && code <= 6) {
        switch (code) {
            case red:
                cout << 0 << endl;
                break;
            case orange:
                cout << 1 << endl;
                break;
            case yellow:
                cout << 2 << endl;
                break;
            case green:
                cout << 3 << endl;
                break;
            case blue:
                cout << 4 << endl;
                break;
            case violet:
                cout << 5 << endl;
                break;
            case indigo:
                cout << 6 << endl;
                break;
            default:
                cout << "輸入有誤,退出" << endl;
                break;
        }
        cout << "跳出選擇\n";
    }
    cout << "跳出迴圈\n";
    return 0;
}


12. 帶回車的字串輸入

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    string input{};
    int count{};

    cout << "請輸入你需要的字元,用*結尾" << endl;
    getline(cin, input, '*');
    count = static_cast<int>(input.length());

    cout << "字元個數為:" << input << endl;

}