C++ C++;检查is编号是否为int/float

C++ C++;检查is编号是否为int/float,c++,C++,我是新来的。我在谷歌上找到了这个网站 #include <iostream> using namespace std; void main() { // Declaration of Variable float num1=0.0,num2=0.0; // Getting information from users for number 1 cout << "Please enter x-axis coordinate locat

我是新来的。我在谷歌上找到了这个网站

#include <iostream>

using namespace std;

void main() {

    // Declaration of Variable
    float num1=0.0,num2=0.0;

    // Getting information from users for number 1
    cout << "Please enter x-axis coordinate location : ";
    cin >> num1;

    // Getting information from users for number 2
    cout << "Please enter y-axis coordinate location : ";
    cin >> num2;

    cout << "You enter number 1 : " << num1 << " and number 2 : " << num2 <<endl;
#包括
使用名称空间std;
void main(){
//变量声明
浮点数num1=0.0,num2=0.0;
//从用户处获取1号的信息
cout>num1;
//从用户处获取第2项的信息
cout>num2;
不能使用类似于

if (static_cast<int>(num1) == num1) {
  // int value
}
else {
  // non-integer value
}
if(静态_转换(num1)=num1){
//整数值
}
否则{
//非整数值
}

输入将被强制转换,以适合您使用cin存储的变量。因为您在num1和num2(浮动)上使用cin,无论用户输入什么数字(在一定程度上),它将是一个浮点数。

如果要检查整数/浮点数的输入,则不应在浮点数中使用cin。相反,将其读入字符串,您可以检查输入是否有效

如果cin读取到一个无效的数字,它将进入失败状态,可以使用If(cin.fail())进行检查

但是,更容易将输入读取为字符串,然后将输入转换为整数或浮点数

isdigit(c)应该在一个字符而不是整数上调用。例如isdigit('1')(注意引号)


您可以使用strtol尝试将字符串转换为整数。根据结果,您可以尝试转换为浮点。

虽然其他人已经回答了这个问题,但我只想指出
isdigit
的真正用途。它告诉您给定的字符是否表示数字

基本上,
isdigit
的定义可以是:

int isdigit (int c)
{
    if (c >= '0' && c <='9')
        return 1;
    else
        return 0;
}

始终读取字符串中的数字,并检查以下内容:-

template <class out_type, class in_type>
out_type convert(in_type const& t)
{
  std::stringstream stream;
  stream << t; // insert value to stream
  // store conversion’s result here
  out_type result;
  stream >> result; // write value to result
  // if there is a failure in conversion the stream will not be empty
  // this is checked by testing the eof bit
  if (! stream.eof() ) // there can be overflow also
  { // a max value in case of conversion error
    result = std::numeric_limits<out_type>::max();
  }
  return result;
}
模板
输出类型转换(输入类型常量和t)
{
std::stringstream;
流>结果;//将值写入结果
//如果转换失败,则流不会为空
//这是通过测试eof位来检查的
如果(!stream.eof())//也可能出现溢出
{//转换错误时的最大值
结果=std::numeric_limits::max();
}
返回结果;
}
它被用作

int iValue = convert<int>(strVal);
if (std::numeric_limits<int>::max() == iValue)
{
  dValue = convert<double>(strVal);
}
int-iValue=convert(strVal);
如果(标准::数值限制::最大()==iValue)
{
D值=转换(标准值);
}

这是一种比较现代的方法:-)

您可以将输入存储到字符串中,然后创建如下函数:

bool GetInt(const char *string, int *out) { char *end; if (!string) return false; int ret_int = strtoul(string, &end, 10); if (*end) return false; *out = ret_int; return true; } bool GetInt(常量字符*字符串,整数*输出) { 字符*结束; 如果(!字符串) 返回false; int ret_int=strtoul(字符串和结束,10); 如果(*结束) 返回false; *out=ret_int; 返回true; } GetInt(“1234”、&somevariable)返回true并将somevariable设置为1234。GetInt(“abc”、&somevariable)和GetInt(“1234aaaa”、&somevariable)都返回false。顺便说一句,这是float的版本:

HOT RESULT_MUST_BE_CHKED NONNULL bool GetFloat(const char *string, float *out) { char *end; if (!string) return false; float ret_float = (float)strtod(string, &end); if (*end) return false; *out = ret_float; return true; } 热结果必须为非空bool GetFloat(const char*string,float*out) { 字符*结束; 如果(!字符串) 返回false; float ret_float=(float)strtod(字符串和结束); 如果(*结束) 返回false; *out=重新浮动; 返回true; }
首先,我会使用cin.fail()方法或通过propper使用异常捕获错误来增强“词法转换”。这实际上非常简单,您不需要在代码中做太多更改:

cout << "Please enter x-axis coordinate location : " << flush;
if (!(cin >> num1)) {
    cout << "You did not enter a correct number!" << endl;
    // Leave the program, or do something appropriate:
    return 1;
}
cout num1)){

cout我想验证输入,并需要确保输入的值是数值,以便可以存储在数值变量中。最后,这对我来说是可行的(来源:

整数;
做{

coutYes。您还必须接受当前区域设置中使用的减号、加号、千位和十进制分隔符(不仅是0-9)可能还应该接受前导空格和尾随空格。这些空格不通过“isdigit”,但仍然可以是输入的有效部分(不过,应该尽早去掉)@Jem:ansic对isdigit的定义不检查加号、减号、分组或十进制分隔符。isdigit仅在参数为数字时返回非零,其他不返回。在您的系统上测试它,看看。正确的数字解析器将使用比isdigit更全面的函数,但我回答的目的只是解释isdigit。Th我评论的目的是:一个人可以使用isdigit检查一个字符是否可以在数字中,只要他“还”检查自己是否有负数,加上…@dreamlax:…并且您还必须记住可能的特定于区域设置的数字格式选项。这是一种糟糕透顶的方法。应该使用
strto…
函数来检查格式的有效性,而不是重新设计轮子并实现手动逐字符检查。
strotol
>不符合标准。此外,我不明白为什么读取字符串然后使用
isdigit
或手动解析应该比检查流的失败状态更容易。@Konrad Rudolph:首先,从什么时候开始
strtol
变得不符合标准?其次,流的失败/成功规范通常与用户需要的。例如,流将允许
123abc
输入,在
a
处停止,而用户可能希望拒绝此类输入。这就是为什么读取字符串然后执行“手动”操作的原因使用
strtol
进行分析在大多数情况下效果更好。@AndreyT不知道为什么我认为
strtol
不是标准的。但是关于您对streams的投诉,解决此问题的方法是检查
eof
。我仍然不明白为什么通过字符串(可能是
strtol
)进行间接寻址应该是正确的“更容易”。@Konrad Rudolph:对于多音输入,这种情况不一定发生在
eof
。我并不是说字符串“更容易”。它更灵活,给人更多的自由。一旦你拥有了字符串,它就不会去任何地方。另一方面,流只能被编辑一次。在我看来,拥有一个多通道的实体来分析(字符串)更好。而且,想想看,ind
cout << "Please enter x-axis coordinate location : " << flush;
if (!(cin >> num1)) {
    cout << "You did not enter a correct number!" << endl;
    // Leave the program, or do something appropriate:
    return 1;
}
//Just do a type cast check
if ((int)(num1) == num1){
//Statements
}
int number;
do{
      cout<<"enter a number"<<endl;
      cin>>number;
      if ((cin.fail())) {
         cout<<"error: that's not a number!! try again"<<endl;
         cin.clear(); // clear the stream
         //clear the buffer to avoid loop (this part was what I was missing)
         cin.ignore(std::numeric_limits<int>::max(),'\n');
         cout<<"enter a number"<<endl; //ask again
         cin>>number;
      }

 } while (cin.fail());