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:

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值