gpt4 book ai didi

c++ - 循环内控制台中的输入和输出

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:20:55 24 4
gpt4 key购买 nike

我正在制作一个 C++ 程序来处理书籍。用户需要插入 3 本书的标题、价格和数量。我没有在代码中包含 Book 类,因为它与我的问题无关。

我卡在了用户需要在循环中输入值的地方。当我测试程序时,控制台似乎在随机时间不断出现故障。 (即它显示 "Give book p" 而不是完整的句子并等待输入)。

我在其他答案中读到我应该在每次 cin>> 调用后使用 cin.ignore() 以忽略 \n 当用户按下 enter 时将其放入流中,但它不能解决我的问题?

知道我做错了什么吗?

#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;
}

控制台示例如下:

Give book title :The HobbitThe HobbitGive book price :12.512.5Give number of volumes :1010Give book title :Lord of the RingsLord of the RingsGive book price :1212Give number of volumes :77Give bo

如您所见,最后一句话被截断,控制台卡在后面。

最佳答案

您可以使用 std::ws 作为您的 getline() 方法的参数来实现您的目标。

以下代码将为您服务:

#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;
}

这将产生以下输出:

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.

关于c++ - 循环内控制台中的输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50365693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com