一个好玩的现象:getline() cannot be used after Cin directly

reference :

Problem with getline() after cin >> - GeeksforGeeksA Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.https://www.geeksforgeeks.org/problem-with-getline-after-cin/The reasons:

The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.

意思是Cin这个函数在调用的时候,会给你的输入自动加一个空格,

而getline()这个函数如果读入的第一个字符是空格,它就默认你的输入结束了

对应的解决方案

The solution to solve the above problem is to use something which extracts all white space characters after cinstd::ws in C++ to do the same thing. This is actually used with the “>>” operator on input streams.

我自己问题的解决方案,是改换他们的位置:

# include <iostream>
# include <iomanip>
# include <string>
using namespace std;
int main()
{
    // Initialize the variables including the number of students and biscuits
    cout << "Number of biscuits" << endl;
    string fullName;
    cout << "Type your full name: ";
    getline (cin, fullName);
    cout << "Your name is: " << fullName;
    int n = 0;
    cin >> n;
}

也就是先做getline()然后在世cin这样就不会有问题了

The outputs:

Number of biscuits
i love you more
the number of biscuits: i love you more
8
Number of students: 8

The codes:

 

# include <iostream>
# include <iomanip>
# include <string>
using namespace std;
int main()
{
    // Initialize the variables including the number of students and biscuits
    cout << "Number of biscuits" << endl;
    string biscuits;
    getline (cin, biscuits);
    cout << "the number of biscuits: " << biscuits << endl;
    int n = 0;
    cin >> n;
    cout <<"Number of students: " << n << endl;
}

挺有意思的,和大家分享

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值