拍卖项目:cin出现C++错误
Auction project: C++ error with cin
我正在做一个项目,该项目假设复制一个拍卖。我想问一下第一个投标人的名字,如果投标人的名字是黑色的,就会给出一条错误消息,说BidderID是空白的。
问题
在询问"Bidder1 ID"后,代码会自动跳过cin,并直接返回错误消息:bidder ID为空。我使用的是我创建的一个名为getName的函数,我认为这是个问题,但代码中使用的其他地方它运行正常。
int main()
{
double bid1, bid2;//declare bid1, bid2
printHeader();
string lotName= getName("Enter lot name: "); //lot name
double reservePrice= getPrice("Reserve price: $");
if (reservePrice<=0) {
printErrorMessage(5);
return 0;
}
cout<<"n";
string bidder1= getName("Bidder 1 ID: "); //bidder1 name
if (bidder1== "") {
printErrorMessage(3);
bid1=0;
}
else {
bid1= getPrice("Bidder1 price: $"); //bidder 1 price
bool lead= isBidPriceGood (bid1, reservePrice); //true if bid1>reservePrice
if (lead==true)
cout<<"n"<<bidder1<<" is high bidder, current price = $"<<bid1<<endl<<endl;
}
string bidder2= getName("Bidder 2 ID: "); //bidder2 name
getline(cin,bidder2);
if (bidder2== "") {
printErrorMessage(3);
bid2=0;
}
else {
bid2= getPrice("Bidder1 price: $"); //bidder 2 price
isBidPriceGood (bid2, reservePrice); //true if bid2>reservePrice
}
//function
string getName(string prompt)
{
string name;
cout<<prompt;
getline(cin,name);
return name;
}
double getPrice(string prompt)
{
string x;
double price;
cout<< prompt;
cin>>price;
getline(cin,x);
return price;
}
void printErrorMessage(int num)
{
if (num == 1) {
cout << endl
<< " ERROR: Reserve not met, bid rejected" << endl << endl;
} else if (num == 2) {
cout << endl
<< " ERROR: Negative price, bid rejected" << endl << endl;
} else if (num == 3) {
cout << endl
<< " ERROR: Blank bidder ID, no bid allowed" << endl << endl;
} else if (num == 4) {
cout << endl
<< "ERROR: Neither bidder met Reserve, auction canceled" << endl << endl;
} else if (num == 5) {
cout << endl
<< "ERROR: Reserve is not positive, auction canceled" << endl << endl;
} else {
cout << " This should never print" << endl << endl;
}
}
getline(cin,name)
将一直读取到下一行。您可能已经在输入流中等待了一条换行符,这是您以前没有读取换行符的输入。例如,您的cin>>price
将读取一个数字,但不会读取该数字之后的换行符,因此,如果对getName
的调用之前是对getPrice
的调用,则价格之后的换行符号仍将等待,而getName
将其视为行的末尾。
为更新的问题编辑:您需要更改此项:
string bidder2= getName("Bidder 2 ID: "); //bidder2 name
getline(cin,bidder2);
仅此而已:
string bidder2= getName("Bidder 2 ID: "); //bidder2 name
你明白为什么了吗?
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'