[C++]-C++基本输入及读取整行

C++标准库提供了一组丰富的输入/输出功能。C++的I/O发生在流中,流是字节序列:

  • 如果字节流是从设备(如键盘、磁盘驱动器、网络连接等)流向内存,这叫做输入操作。
  • 如果字节流是从内存流向设备(如显示屏、打印机、磁盘驱动器、网络连接等),这叫做输出操作。

标准输入流

预定义的cin 是 iostream 类的一个实例。cin 对象附属到标准输入设备,通常是键盘;cin 与流提取运算符>>结合使用。

cin>>

cin默认使用空白(空格、制表符、换行符)来确定字符串的结束位置:

#include <iostream>
using namespace std;

void testInput(){
    int nAge;
    double height;
    string name;
    cout<<"Input Age, height, name: "; // 12 1.65 mike josn
    cin>>nAge>>height>>name;
    cout<<"Age: "<<nAge<<", Height: "<<height<<", Name: "<<name<<endl;
    // 12 1.65 mike
}

读取name时,只读取前面一部分(因空格结束了字符串的读取)。

cn.get

cin.get()可以读取每个字符返回,也可把读取的内容放到字符参数中:

int_type get();
basic_istream& get (char_type& c);

cin.get()依次读取每一个字符,直到结束(Ctrl+z):

void testGet(){
    cout<<"Input: ";
    int nGet;
    while( (nGet=cin.get())!=EOF){ // 输入回车时,才依次读取(回车符本身也作为一个字符读取到
        cout<<(int)nGet<<endl;
    }
}

整行读取

std::getline可以读取一行放入string中,cin.get与cin.getline可以读取一行放入到字符数组中。

std::getline

std::getline从输入流中读取字符到string中,直到遇到分隔符(默认\n):

istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);

若指定分隔符(如设为空格),可用于字符串分割:

#include <iostream>
#include <sstream>
using namespace std;

void testLine(){
    cout<<"Input: ";
    string strIn;
    std::getline(cin, strIn);
//    cout<<strIn;
    
    string strWord;
    istringstream is(strIn);
    while(std::getline(is, strWord, ' ')){
        cout<<strWord<<endl;
    }
}

cin.getline

cin.getline从输入流中读取字符到字符数组,直到遇到分隔符(默认\n)或数组最大长度-1;末尾会自动添加NULL;通过gcount可获取读取字符数(包括分隔符):

basic_istream& getline (char_type* s, streamsize n );
basic_istream& getline (char_type* s, streamsize n, char_type delim);

字符数组中不包含分隔符(且已从输入缓冲区中删掉了),但gcount包括分隔符(即:len(ary)+1):

    char strIn[1024];
    for(int i=0; i<5; ++i) {
        cin.getline(strIn, 1024);
        cout << "count: " << cin.gcount() << endl;
    }

cin.get

cin.get从输入流中读取字符到字符数组,直到遇到分隔符(默认\n)或数组最大长度-1;末尾会自动添加NULL:

basic_istream& get (char_type* s, streamsize n);
basic_istream& get (char_type* s, streamsize n, char_type delim);

cin.get读取时,会把分隔符留在缓冲区中,若不主动去掉,则会一直读取空字符串:

    char strIn[1024];
    for(int i=0; i<5; ++i) {
        cin.get(strIn, 1024).get();
    }

若没有后面的get(),则在读取一行后,后续一直读取空(因换行符还在缓冲区中)。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值