在 C++ 中,我的程序自动转到下一个 CIN 提示符,而不让用户添加输入
In c++, my program automatically goes to the next CIN prompt without letting the user add input
这是我的代码:
#include <iostream>
using namespace std;
const int SENIOR_PRICE = 9;
const int ADULT_PRICE = 12;
const float CHILD_PRICE = 6.95;
const float TAX_RATE = .06;
int main()
{
string name;
string address;
int numSeniorTickets;
int numAdultTickets;
int numChildTickets;
cout << "Enter customer name:" << endl;
cin >> name;
cout << "Enter customer address:" << endl;
cin >> address;
cout << "How many senior season tickets?" << endl;
cin >> numSeniorTickets;
cout << "How many adult tickets?" << endl;
cin >> numAdultTickets;
cout << "How many child tickets?" << endl;
cin >> numChildTickets;
return 0;
}
用户输入姓名后,系统会提示他们输入地址。但在他们输入地址之前,它还会提示输入高级季票的数量。为什么它会跳过一行输入?这是发生了什么:
Enter customer name:
Daniel Benson
Enter customer address:
How many senior season tickets?
5
How many adult tickets?
5
How many child tickets?
5
cin >> name;
最多只接受输入 space。因此,如果您打印变量 name
,您将得到 Daniel
。如果您打印变量 address
,您将得到 Benson
。因此,就程序而言,它已将两个字符串作为输入。
A proof of the above statements by printing the variables after input.
您可能希望使用 cin.getline() 将 space 分隔的字符串作为输入。
这是我的代码:
#include <iostream>
using namespace std;
const int SENIOR_PRICE = 9;
const int ADULT_PRICE = 12;
const float CHILD_PRICE = 6.95;
const float TAX_RATE = .06;
int main()
{
string name;
string address;
int numSeniorTickets;
int numAdultTickets;
int numChildTickets;
cout << "Enter customer name:" << endl;
cin >> name;
cout << "Enter customer address:" << endl;
cin >> address;
cout << "How many senior season tickets?" << endl;
cin >> numSeniorTickets;
cout << "How many adult tickets?" << endl;
cin >> numAdultTickets;
cout << "How many child tickets?" << endl;
cin >> numChildTickets;
return 0;
}
用户输入姓名后,系统会提示他们输入地址。但在他们输入地址之前,它还会提示输入高级季票的数量。为什么它会跳过一行输入?这是发生了什么:
Enter customer name:
Daniel Benson
Enter customer address:
How many senior season tickets?
5
How many adult tickets?
5
How many child tickets?
5
cin >> name;
最多只接受输入 space。因此,如果您打印变量 name
,您将得到 Daniel
。如果您打印变量 address
,您将得到 Benson
。因此,就程序而言,它已将两个字符串作为输入。
A proof of the above statements by printing the variables after input.
您可能希望使用 cin.getline() 将 space 分隔的字符串作为输入。