当前位置:C++技术网 > 资讯 > C++代码系统:cin

C++代码系统:cin

更新时间:2019-04-26 11:13:10浏览次数:1+次

代码名称:
cin

代码功能:
演示cin的各种使用使用方式,包括读取基本数据类型、读取单个字符、读取char数组、读取string、读取含空白字符字符串、读取一行等

源代码:

#include <iostream>
using namespace std;
int main()
{
    int a;
    double b;
    bool bl;
    char c;
    char buf[100];
    string str;

    //基本数据类型的输入
    cin >> a;
    cin >> b;
    cin >> bl;//不能输入true和false,输入1或0
    cin >> c;
    cin >> buf;
    cin >> str;

    cout << a << endl;
    cout << b << endl;
    cout << boolalpha << bl << endl;
    cout << c << endl;
    cout << buf << endl;
    cout << str << endl;

    //含空白字符的输入,空白字符:空格 回车 制表符
    cin >> buf;//hello world 或 hello[回车]world 或 hello[Tab制表符]world
    cout << buf << endl;//输出hello
    
    //读取一行,包括空白符,不含换行符
    cin.getline(buf, 100);
    //hello world --> 输出hello world
    //hello[回车]world -->输出hello
    //hello[Tab制表符]world -->输出hello    world
    cout << buf << endl;

    //读取单个字符
    cin >> c;
    cin.get(c);
    c = cin.get();

    return 0;
}

代码说明:

输入结束条件:遇到Enter、Space和Tab键。

    程序的输入都建有一个缓冲区,即输入缓冲区。一次输入过程是这样的,当一次键盘输入结束时会将输入的数据存入输入缓冲区,而cin函数直接从输入缓冲区中取数据。正因为cin函数是直接从缓冲区取数据的,所以有时候当缓冲区中有残留数据时,cin函数会直接取得这些残留数据而不会请求键盘输入。


备注:
cin.get()可用于暂停输入,过滤空白字符。