使用getline(),它跳转到下一件事。 C ++ [英] using getline(), it jumps to the next thing. c++

查看:75
本文介绍了使用getline(),它跳转到下一件事。 C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我使用get line来获取字符串DOB。但是当我编译并执行它时,它不会接受DOB的输入,而是跳转到下面的函数。

  int 乌塞林; 
字符串名称;
字符串名字;
string lastname;
string dob;

bool exit_b = false ;
while (exit_b == false ){

cout< < \ n使新客户输入:1<< endl;
cout<< \ n使新员工输入:2<< ; ENDL;
cin>> userin;

if (userin == 1
{
cout<< 输入名字:<< endl;
cin>> firstname;

cout<< 输入姓氏:<< ENDL;
cin>> lastname;
name = firstname + + lastname;


cout<< Date Birth:< ;< ENDL; // 此事应该采取用户输入
getline(cin,dob); // 但是这个东西没有输入它跳转到代码的下一部分

客户客户(name,dob,rand()%10000);
customer.print_detail();
}

解决方案

使用带有getline(cin,variable)的流运算符始终是个问题,因为有些数据仍然在输入中缓冲。所以你应该删除那里的所有内容然后阅读你的输入。



 (getline(cin,dob))
if (dob!= < span class =code-string>)
break ; // 我们得到的东西


在调用 getline

 cin.sync(); 


您需要在使用getline之前刷新缓冲区。查看 [ ^ ]供参考!


Hi I am using get line to get a string DOB. but when i compile and execute it doesnt take input for DOB but jumps to the function below.

    int userin;
    string name;
    string firstname;
    string lastname;
    string dob;

	bool exit_b= false;   
while(exit_b == false){

    cout<<"\nmake a new customer enter: 1"<<endl;
    cout<<"\nmake a new staff enter: 2"<<endl;
    cin>>userin;

    if(userin ==1)
        {
            cout<<"Enter First Name: "<<endl;
            cin>>firstname;

            cout<<"Enter Last Name: "<<endl;
            cin>>lastname;
            name = firstname + " " + lastname;


            cout<<"Date Birth: "<<endl; //this thing should take user input
            getline(cin,dob);   //but this thing doesnt take input it jumps to the next part of the code

            Customer customer(name, dob, rand()%10000);
            customer.print_detail();
        }

解决方案

Using stream operators with getline(cin, variable) is always a problem because some data remains in the input buffer. So you should remove everything still in there then read your input.
I.e.

while (getline(cin, dob))
  if (dob != "")
    break;    //we got something


An alternative way of flushing the buffer before calling getline

cin.sync();


You need to flush the buffer before using getline. Check this[^] for reference!


这篇关于使用getline(),它跳转到下一件事。 C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆