cin.getline和getline区别

 1.cin.getline()函数cin.getline(字符数组名,字符个数,结束标志),结束标志可以省略,碰到回车就会停止。
  cin.getline()可以接收空格,直到碰到回车才停止,所以会读取n-1个元素。

#include <iostream>
using namespace std;
int main() {
  char a[100] ;
cout<<"输入的值为:"<<end;
    cin.getline(a, 10);
    for(int i = 0; i<10;i++)
    cout << "输出的值:"<<a[i]<< endl;
    return 0;
}

用户端输入的字符不足给定的元素个数,则只截取用户的元素,如果用户端输入的字符数目大于给定的,则按照给定的数目截取,空格也算在内。

结果:

D:\untitled19\cmake-build-debug\untitled19.exe
输入的值:1 2 3456789
输出的值:
1

2

3
4
5
6
7


Process finished with exit code 0

2.(1) getline()函数getline(cin, str)  将输入流保存到str中去,过程中空格也一并接收可读取整行,

包括前导和嵌入的空格,并将其存储在字符串对象中。

#include <iostream>
#include <string> //来导入标准库中的字符串类和相关操作,导入后才能使用string类
using namespace std;
int main()
{
    string name;
    string city;
    cout << "Please enter your name: ";
    getline(cin, name);
    cout << "Enter the city you live in: ";
    getline(cin, city);
    cout << "Hello, " << name << endl;
    cout << "You live in " << city << endl;
    return 0;
}

运行结果:

D:\untitled39\cmake-build-debug\untitled39.exe
 Please enter your name: jan
 Enter the city you live in: Beijing
 Hello, jan
You live in Beijing

Process finished with exit code 0

  (2) 当同时使用cin和getline时,在输入流cin结束后需要清空缓存,否则下一个读入的并不是用户的输入而是一个回车。 例如:

#include <iostream>
#include <string> 
using namespace std;
int main()
{
    string c;
    int a;
    cin>>a;
    getline(cin, c);
    cout<<c<<endl;
    return 0;
}

运行结果:

D:\untitled39\cmake-build-debug\untitled39.exe
5


Process finished with exit code 0

输入流赋值给a后,本想通过getline获取c,却没有机会再进行输入了,这是因为cin之后的回车交给了c, 程序结束

 解决方法是插入一个函数用来接收\n,然后再调用自己的getline函数来接收之后的string c;

测试结果: 

D:\untitled39\cmake-build-debug\untitled39.exe
2
b
b

Process finished with exit code 0

  • 8
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值