gpt4 book ai didi

C++ cin 仅限正整数

转载 作者:太空狗 更新时间:2023-10-29 21:49:58 26 4
gpt4 key购买 nike

这是我第一次使用 Stackoverflow。我正在制作一个程序来找出汽车的 MPG。我想知道如何让 cin 语句只接受正整数?还有,如果你确实输入了无效的输入,你能重置它吗?我不确定这是否有意义。我不必在类里面这样做。我只是好奇如何去做。这是代码。

#include <iostream>
using namespace std;

int main()
{
double tank, miles, mpg;

cout << "Hello. This is a program that calculates the MPG ( Miles Per Gallon) for your\n" ;
cout << "vehicle\n" << endl;
cout << "Please enter how many gallons your vehicle can hold\n" << endl;
cin >> tank;
cout << endl;
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl;
cin >> miles;
cout << endl;

mpg = (miles)/(tank);
cout << "Your vehicle recieves " << mpg << " miles per gallon\n" << endl;
system ("pause");
return 0;
}

最佳答案

iostreams 不是用于构建复杂 UI 的工具包。除非您想编写自己的相当复杂的流来包装通常的流,否则您无法让它 (a) 只接受正整数或 (b) 礼貌地与输入其他内容的用户交互。

你应该只从 cin 中读取行,然后打印你自己的错误提示等等。

关于C++ cin 仅限正整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7354009/

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