c++中getline()、cin.getline()、cin.get()输入问题总结

一、getline()用法

函数原型:

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

函数描述

Get line from stream into string.
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, ‘\n’, for (2))

is中提取字符并将其存储到str中,直到找到定界字符delim(默认为换行字符’\n’)
如果在is中到达文件末尾,或者在输入操作期间发生其他错误,提取也会停止。
如果找到分隔符delim,则提取并丢弃它(即不存储它,下一个输入操作将在它之后开始)。

getline()这个函数是可以读取空格,遇到换行符或者EOF结束,但是不读取换行符的

应用举例

从输入流读取一行字符串,通过逗号分隔
输入:

a,b,d,11,2d

将各字符串输出到string的vector数组里

#include <sstream>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    string str1;
    getline(cin,str1); //通过getline()将回车符前的输入流读到str1中
    sstring ss(str1);
    
    vector<string> vc;
    string sub;
    while(getline(ss,sub,','))  //
    {
        vc.push_back(sub);
    }
    for (auto iter = vc.begin(); iter != vc.end(); iter++)
    {
        cout << *iter << endl;
     }


    return 0;
}

运行结果:
在这里插入图片描述

二、cin.getline()与cin.get()比较

cin.getline(arrayname,size)
cin.getline(arrayname,size,s)

把数据输入到arrayname字符数组中,当到达长度size时结束或者遇到字符s时结束.
arraynam必须是char []类型
cin.getline(arrayname,size)当遇到[enter],[space],[tab]时会结束当前输入,但是会删除缓冲区中的[enter]
cin.get(arrayname,size)当遇到[enter],[space],[tab]时会结束目前输入,他不会删除缓冲区中的[enter]

#include<iostream>
using namespace std;
 
int main()
{
	char a[10];
    char b;
    cin.getline(a,10);
	cin.get(b);
	cout<<a<<endl<<int(b);
}

输入:12345[enter]a[enter]
输出结果:12345【换行】97

说明:
cin.getline(a,10)将遇到[enter]前的12345读入到a中,并忽略[enter];
cin.get(b)一次只能读取一个字符,将字符’a’读入到b中。

三、清空缓冲区

cin.ignore(numeric_limits<std::streamsize>::max(),'\n');//清除输入缓冲区的当前行 

numeric_limitsstd::streamsize::max() 可替换为一个足够大的数

当上一次cin>>a读取完以后,缓冲区依旧保留有[enter],为了下一次能够正确使用getline()函数,需要将这个[enter]清空

int main()
{
       int a;
       cin >> a;
       string str1;
       getline(cin, str1);
       cout << "a=" << a << endl;
       cout <<"str="<< str1;

       return 0;
}


如果输入:2[enter]a,b,c,d[enter]
输出为:
在这里插入图片描述
getline()读取的是2后面的那个[enter],因此str1为空字符串。
修改:

int main()
{
       int a;
       cin >> a;
       string str1;
       cin.ignore(numeric_limits<std::streamsize>::max(), '\n');//清除输入缓冲区的当前行 
       getline(cin, str1);
       cout << "a=" << a << endl;
       cout <<"str="<< str1;

       return 0;
}


输出结果:
在这里插入图片描述
str1正确读取到了字符串

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值