[英]Input and output in console inside a loop
I am making a C++ program to handle books. 我正在制作一个C ++程序来处理书籍。 The user needs to insert the title, price and volumes for 3 books.
用户需要插入3本书的标题,价格和数量。 I don't include the
Book
class in the code as it is not relevant with my problem. 我没有在代码中包含
Book
类,因为它与我的问题无关。
I am stuck in the place where the user needs to input the values inside the loop. 我被困在用户需要在循环内输入值的地方。 When I test the program the console keeps bugging at seemingly random times.
当我测试程序时,控制台在看似随机的时间里保持窃听。 (ie it shows
"Give book p"
instead of the full sentence and awaits for input). (即它显示
"Give book p"
而不是完整的句子并等待输入)。
I read in other answers that I should use cin.ignore()
after every cin>>
call in order to ignore the \\n
that is put on the stream when the user presses enter, but it doesn't solve my problem? 我在其他答案中读到我应该在每次
cin>>
调用之后使用cin.ignore()
来忽略当用户按下回车时放在流上的\\n
,但它不能解决我的问题?
Any ideas what I am doing wrong? 我有什么想法我做错了吗?
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string title;
double price;
int volumes;
for (int i=0; i<3;i++){
cout << "Give book title : " << endl;
getline (cin, title);
cout << "Give book price : " << endl;
cin >> price;
cin.ignore();
cout << "Give number of volumes : " << endl;
cin >> volumes;
cin.ignore();
}
return 0;
}
Following is an example of the console : 以下是控制台的示例:
Give book title : The Hobbit The Hobbit Give book price : 12.5 12.5 Give number of volumes : 10 10 Give book title : Lord of the Rings Lord of the Rings Give book price : 12 12 Give number of volumes : 7 7 Give bo
As you can see the last sentence is cut off and the console is stuck after. 正如你所看到的那样,最后一句被切断,控制台被卡住了。
You can use std::ws
as a parameter to your getline()
method to achieve your objective. 您可以使用
std::ws
作为getline()
方法的参数来实现您的目标。
The following code will serve your purpose: 以下代码将满足您的目的:
#include <iostream>
int main() {
std::string title;
double price;
int volumes;
for (int i=0; i<3;i++){
std::cout << "Give book title : ";
std::getline(std::cin >> std::ws, title);
std::cout << "Give book price : ";
std::cin >> price;
std::cout << "Give number of volumes : ";
std::cin >> volumes;
std::cout<<"Title: "<<title<<" costs "<<price<<" for "<<volumes<<" volumes.\n";
}
return 0;
}
This will produce the following output: 这将产生以下输出:
Give book title : Harry Potter
Give book price : 12.5
Give number of volumes : 5
Title: Harry Potter costs 12.5 for 5 volumes.
Give book title : James Anderson
Give book price : 45.6
Give number of volumes : 7
Title: James Anderson costs 45.6 for 7 volumes.
Give book title : Lucas Empire
Give book price : 34.5
Give number of volumes : 7
Title: Lucas Empire costs 34.5 for 7 volumes.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.