天天看點

C++之cin.get()用法

/**
 *********************************************************************
 * @file     cin_get.cpp
 * @author   Zhen Haiyang
 * @version  1.0
 * @date     2021-05-25 00:18:07
 * @brief    cin.get()使用方法
 *********************************************************************
 */

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    /* 1.讀取一個字元 */
    char c;

    cout << "Enter the character 1: ";
    cin.get(c);
    cout << "The code of the character 1 is: " << int(c) << endl;

    cout << "Enter the character 2: ";
    c = cin.get();
    cout << "The code of the character 2 is: " << int(c) << endl;

    /* 2.讀取一行字元串 */
    char cs[10];

    cout << "Enter the string 1: ";
    cin.get(cs, 10).get();
    cout << "The string 1 is: " << cs << endl;

    cout << "Enter the string 2: ";
    cin.get(cs, 10).get();
    cout << "The string 2 is: " << cs << endl;

    /* 3.處理每個字元 */
    cout << "Enter the string 3: ";
    cin.get(c);
    cout << "The string 3 is: ";
    while (cin)
    {
        cout << c;
        cin.get(c);
    }
    cout << endl;
    cin.clear(); //清除之前的退出狀态

    /* 4.處理每個字元串 */
    int i = 4;
    cout << "Enter the string 4: ";
    cin.get(cs, 10);
    while (cin)
    {
        cin.get(); //讀取掉回車
        cout << "The length of the string " << i++ << " is: " << strlen(cs) << endl;
        cout << "Enter the string " << i << ": ";
        cin.get(cs, 10);
    }

    return 0;
}
           

結果:

Enter the character 1: A
The code of the character 1 is: 65
Enter the character 2: The code of the character 2 is: 10
Enter the string 1: zhen
The string 1 is: zhen
Enter the string 2: hai
The string 2 is: hai
Enter the string 3: yang
The string 3 is: yang
^Z

Enter the string 4: zhen
The length of the string 4 is: 4
Enter the string 5: hai
The length of the string 5 is: 3
Enter the string 6: yang
The length of the string 6 is: 4
Enter the string 7: