C++之cin.get()用法

Posted 海洋想想

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

以上是关于C++之cin.get()用法的主要内容,如果未能解决你的问题,请参考以下文章

C++中cin、cout的一些特殊用法

C++输入cin详解

C++字符串输入详解!

cin.get ()的用法:

cin.get()解密

c++中 cincin.get()cin.getline()cin.getchar()的区别