如何检查一个C ++字符串是否是一个int? [英] How do I check if a C++ string is an int?

查看:153
本文介绍了如何检查一个C ++字符串是否是一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 getline 时,我会输入一串字符串或数字,但我只想要while循环输出word,如果它不是一个数字。
所以有什么办法来检查字是否是一个数字?我知道我可以使用 atoi()
C字符串,但对字符串类的字符串如何?

When I use getline, I would input a bunch of strings or numbers, but I only want the while loop to output the "word" if it is not a number. So is there any way to check if "word" is a number or not? I know I could use atoi() for C-strings but how about for strings of the string class?

int main () {
  stringstream ss (stringstream::in | stringstream::out);
  string word;
  string str;
  getline(cin,str);
  ss<<str;
  while(ss>>word)
    {
      //if(    )
        cout<<word<<endl;
    }
}


推荐答案

version ...

Another version...

使用 strtol ,将其包装在一个简单的函数中以隐藏其复杂性:

Use strtol, wrapping it inside a simple function to hide its complexity :

inline bool isInteger(const std::string & s)
{
   if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false ;

   char * p ;
   strtol(s.c_str(), &p, 10) ;

   return (*p == 0) ;
}



为什么 strtol



至于我喜欢C ++,有时C API是我所关心的最好的答案:

Why strtol ?

As far as I love C++, sometimes the C API is the best answer as far as I am concerned:


  • 对于被授权失败的测试,使用异常是过度的。

  • 由于词法转换,临时流对象的创建是过度的,

strtol 看起来相当原始,所以解释会使代码更容易阅读:

strtol seems quite raw at first glance, so an explanation will make the code simpler to read :

strtol 将解析字符串,停止在不能被视为整数的一部分的第一个字符。如果你提供 p (如上所述),它在这个第一个非整数字符处设置 p

strtol will parse the string, stopping at the first character that cannot be considered part of an integer. If you provide p (as I did above), it sets p right at this first non-integer character.

我的推理是如果 p 没有设置为字符串的结尾(0字符)是字符串 s 中的非整数字符,表示 s 不是正确的整数。

My reasoning is that if p is not set to the end of the string (the 0 character), then there is a non-integer character in the string s, meaning s is not a correct integer.

第一个测试是消除角落情况(前导空格,空字符串等)。

The first tests are there to eliminate corner cases (leading spaces, empty string, etc.).

这个函数当然应该根据你的需要定制(前导空格有错误等)。

This function should be, of course, customized to your needs (are leading spaces an error? etc.).

请参阅 strtol 的说明: http://en.cppreference.com/w/cpp/string/byte/strtol

也请参阅 strtol 的姊妹函数( strtod strtoul 等)。

See, too, the description of strtol's sister functions (strtod, strtoul, etc.).

这篇关于如何检查一个C ++字符串是否是一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆