跳过第一条提示

时间:2018-09-22 23:48:21

标签: c++ console-application

美好的一天,

我正在为学校项目编写此代码,但是在编译并执行该代码后,单击“是”后,我无法输入名称。 我不确定为什么这种情况发生在代码块和社区中。 我试过添加cin.ignore();在getline(cin,customer)下面,它有点用,但是我无法输入公司名称。如果我都将cin.ignore()放在两者上,则输入数字字段将被跳过,并将直接进入结果。 我将在下面附加图片(不使用cin.ignore)enter image description here

       #include "pch.h"
       #include <iostream>
       #include <string>
       #include <cstdlib>
       #include <ctime>

       using namespace std;

       int main()
{

string input;
cout << "hello, press yes to start or no to cancel \n";
cin >> input;

if (input == "no")
{
    cout << "have a nice day \n";
}
else if (input == "yes")
{
    string customer;
    string address;
    int user_enter_number;
    const double pc = 0.05 * 10;
    double amount, abacus, price; // abacus = AMOUNT
    time_t now; // rawtime
    struct tm nowlocal;


    cout << "Please enter your name " << endl;
    getline(cin, customer);   ` when executing, I was not able to type my 
                               name and instead was skipped and went to 
                               enter the store's name.`

    cout << "Please enter the store's name \n"; 
    getline(cin, address);

    cout << "Please enter the number you would like to buy, the range is 
    from 00 - 99 \n";
    cin >> user_enter_number;

    cout << "Please enter the amount you wish to spend ($): \n";
    cin >> amount;

    abacus = amount * pc;
    price = amount;

    now = time(NULL); // obtains the time from the operating system
    nowlocal = *localtime(&now);

    cout << customer << " you have bought this number: " << 
    user_enter_number << endl;
    cout << "you have bought this pcs: " << amount / 0.05 << endl;
    cout << "this ticket was bought on: " << nowlocal.tm_mday << "/" << 
    nowlocal.tm_mon + 1 << "/" << nowlocal.tm_year + 1900 << endl;
    cout << "at this time: " << nowlocal.tm_hour << ":" << nowlocal.tm_min << ":" << nowlocal.tm_sec << endl;

    srand(time(NULL));

    int min = 00;
    int max = 99;
    int num = (min + (rand() % (int)(max - min + 1)));

    cout << "the winning number is: " << num << endl;

    if (num == user_enter_number)
    {
        cout << customer << " You have won" << amount << "Please visit your 
         nearest store to collect! \n";
    }
    else
    {
        cout << "Try again next time! \n";
    }

     return 0;
}    

1 个答案:

答案 0 :(得分:0)

输入的第一行是一行。也使用getline。

cin >> input;

将换行符保留在缓冲区中。

getline(cin, customer);

只能从第一个输入中读取换行符。