在c ++中验证double [英] Validating a double in c++
问题描述
我完全不熟悉编码,因此在注释之前请记住这一点。
I'm completely new to coding, so please keep this in mind before commenting.
所以我一直试图进入编码一段时间,今天我去图书馆
并拿起一本书叫c ++编程。我写了一些基本的程序,
,但我陷入了一点,我不知道如何创建一个函数
确保当用户提示双,他们进入已验证。
(如果用户输入k这样的字符,程序就会中断)。
我在这里和网上搜索,并有一些答案,但他们更多沿着
这里的一行代码工作,插入x,y,z到它的行。而我不
有足够的经验知道该怎么办。所以这里是一个混合代码
从另一个问题,我没有尝试使其工作在我的程序:
So I've been trying to get into coding for a while, and today I went to the library and picked up a book called "programming in c++". I've written some basic programs, but I have gotten stuck at one point, I have no idea how to create a function that makes sure that when the user is prompted for a double, what they enter is valid. (If the user enters a character like 'k', the program just breaks). I searched here and on the net, and there are some answers, but they are more along the line of "here's a line of code that works, insert x, y, z, into it". And I don't have enough experience to know what to do. So here is a sample that is a mix of code from another question, and me failing to try to make it work in my program:
#include <iostream>
#include <stdio.h>
using namespace std;
double GetDouble () {
double x;
cin >> x;
int valid = 0;
while (valid == 0) {
if (x == double) {
return x;
break;
} else if (x != double) {
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while (cin.get() != '\n') ; // empty loop
}
}
return x;
}
现在我想要做的是使用cin< x来获得用户对x的输入,然后
然后确保x是双精度,我在这里失败了。如果
有人可以解释这一点,以澄清每个操作,
我会真正感谢。例如,我不知道break函数的作用,
和cin.clear()和cin.get()做什么。 (我知道这是一个重复,但在另一个问题的
答案根本不说明我很困惑,
谢谢你花时间阅读& answer this!:
Now what I want it to do is to use "cin << x" to get a user input for x, and then make sure that x is a double, and I'm failing quite hard at this. If someone could explain this to in a manner that clarifies each operation, I would be truly grateful. For example, I don't know what the break function does, and what the cin.clear(), and cin.get() do. (I know this is a duplicate, but the answers on the other question does not at all address what I'm confused about, thank you for taking time to read & answer this! :)
推荐答案
这似乎是你的代码的一个接近的模拟(大部分):
This seems a close analog to your code that (mostly) works:
double GetDouble () {
double x;
cin >> x;
// ver1: while( cin.fail() ) // or !cin.good() no trailing char check.
while( cin.fail() || (cin.peek() != '\r' && cin.peek() != '\n'))
{
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while( cin.get() != '\n' ); // or cin.ignore(1000, '\n');
cin >> x;
}
return x;
}
这篇关于在c ++中验证double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!