如何在c++中检查输入值是否为有效值
how to check if inputed value is valid value in c++
我检查了Stack和其他网站上的许多链接。大部分都是按照应该做的去做,但并不是"完全"按照我的意愿去做。以下是我在网上找到的问题和最佳解决方案。我想输入一个数字,例如float,并且应该检查输入是否为float。我正在使用网上找到的这个片段。还需要提到的是,每次循环迭代时,我都需要重复验证。"n"是在这个函数之前单独输入的,它在"private"中。它完美地完成了它的工作,除了。。。如果您输入"55"(数字),它将进行检查和验证。没关系。若您输入"dfgfd"内容(不是数字),它会检查并重复问题。没关系。若您输入"dfgdfgdg55",它会检查并重复问题。也可以。如果你输入"55dfgfd"的内容,它会检查而不会重复。这不好。它只是在数字后面丢弃字符。我也想放弃这个。因此,正确的输入应该是JUST"55"输入。(数字55只是提示时输入的一个示例数字)。我还在一个更简单的函数"model"上尝试了这个。首先输入"55",第二输入"55gdf"。它们在屏幕上显示为"55"answers"55"。然后我添加了一些代码来比较这些数字。他们不一样!
#include <iostream>
using namespace std;
int Provera_kucanja()
{
cout<<endl;
cout<<"Input boundary for an array"<<endl;
cin>>n;
while (cin.fail() || !(n>0))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout<<"You didnt entered number, please try again... "<<endl;
cin>>n;
}
cout<<endl;
return 0;
}
float Unos_brojeva()
{
cout<<"n";
cout<<"Now you must enter number into array:n "<<endl;
for (int i = 0; i < n ; i++)
{
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
float r;
cin>>r;
while (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout<<"You didnt entered number, please try again... "<<endl;
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
cin>>r;
}
unos[i]=r;
}
cout<<endl;
cout<<"Now show unsorted array members: "<<endl;
for(int i = 0; i < n; i++)
{
cout<<"This is "<<"["<<i<<"]"<<" member of array named 'unos': "<<unos[i]<<endl;
}
cout<<"n"<<endl;
cin.get();
return 0;
}
int main(){
Provera_kucanja();
Unos_brojeva();
}
使用建议答案的不利方面是,当用户输入类似"ghfg"的内容时,此转换的结果为零!。因此,建议的答案是否定的。
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string A_number;
char* An_array=new char[A_number.length()];
cout<<"Enter value for A_number: ";
cin>>A_number;
strcpy(An_array,A_number.c_str());
float n=atof(An_array);
cout<<"Value entered is: "<<n;
cin.get();
return 0;
}
行:
cin >> r
将尝试读取一个有效的浮点值,即使后面有错误的尾随信息。
你是说当有人输入55x
时就会出现问题,在这种情况下,你认为它不应该被视为有效的数字。
这里有你的问题的答案:https://stackoverflow.com/a/19717896/312594
您要做的是将整个数据作为字符串读取,并确认输入中只有可能作为浮点输入的字符(digits
、.
、+
、-
等),并且顺序正确。只有在验证了输入之后,才能将输入转换为float(通过cin
或其他机制)。
在大多数情况下,你应该接受55x作为55,因为这可能是用户想要的,但如果你想严格要求,你必须自己进行额外的验证。
p.s.-我几乎不想这么说,因为我不想听起来有偏见,但当你学习C++时,你可能会发现用英语编写所有代码(包括提示)很有用。如果你以后在StackOverflow上寻求帮助,更多的人会更容易理解你想做什么,从而帮助你。
听起来你想以字符串(或整行)的形式读取输入,然后你可以随心所欲地测试这些字符串。
- 如何检查QList中是否存在值
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 钳制迭代器是否有效
- 检查由括号、方括号和大括号组成的一组方括号是否有效?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 模板签名解析为 void(void) 被 GCC 拒绝;这是否有效C++?
- 我如何知道作为参数的size_t在函数中是否有效?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- C++17:使用 std::optional 来评估枚举是否包含值
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 此递归模板类型定义是否有效C++?
- 在函数中按值传递 unordered_map/unordered_set 是否有效? C++
- 移动后右值是否有效?
- 如何检查用户是否输入了有效值
- 使用无符号数据类型强制执行非负值和/或有效值是否是一种最佳做法
- 指针指向0x1 - 正在检查空值是否有效
- 如何在c++中检查输入值是否为有效值
- 在c++ 11中将非const左值引用绑定到右值是否有效?(修改)
- 在函数调用中省略参数值是否有效?
- 将函数指针上的参数与默认值参数一起丢弃是否有效