c++从字符串中解析int

发布于 2024-10-08 02:12:09 字数 451 浏览 4 评论 0 原文

可能的重复:
如何在 C++ 中将字符串解析为 int?< /a>

我做了一些研究,有些人说使用 atio,另一些人说它不好,而且我无论如何也无法让它工作。

所以我只想问一下,将字符串转换为 int 的正确方法是什么。

string s = "10";
int i = s....?

谢谢!

Possible Duplicate:
How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

string s = "10";
int i = s....?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

余生共白头 2024-10-15 02:12:09
  • 在 C++11 中,使用 std::stoi为:

     std::string s = "10";
     int i = std::stoi(s);
    

    请注意,如果无法执行转换,std::stoi 将抛出 std::invalid_argument 类型的异常,或者 std::out_of_range > 如果转换导致溢出(即当字符串值对于 int 类型来说太大时)。您可以使用 std::stolstd:stoll 但以防万一 int 对于输入字符串来说似乎太小。

  • 在 C++03/98 中,可以使用以下任何一种:

     std::string s = "10";
     整数我;
    
     //方法一
     std::istringstream(s)>>我; //此后i为10
    
     //方法二
     sscanf(s.c_str(), "%d", &i); //此后i是10
    

请注意,对于输入 s = "10jh",上述两种方法都会失败。他们将返回 10 而不是通知错误。因此,安全可靠的方法是编写自己的函数来解析输入字符串,并验证每个字符以检查它是否是数字,然后进行相应的工作。这是一个强大的实现(尽管未经测试):

int to_int(char const *s)
{
     if ( s == NULL || *s == '\0' )
        throw std::invalid_argument("null or empty string argument");

     bool negate = (s[0] == '-');
     if ( *s == '+' || *s == '-' ) 
         ++s;

     if ( *s == '\0')
        throw std::invalid_argument("sign character only.");

     int result = 0;
     while(*s)
     {
          if ( *s < '0' || *s > '9' )
            throw std::invalid_argument("invalid input string");
          result = result * 10  - (*s - '0');  //assume negative number
          ++s;
     }
     return negate ? result : -result; //-result is positive!
} 

此解决方案是 my另一种解决方案

  • In C++11, use std::stoi as:

     std::string s = "10";
     int i = std::stoi(s);
    

    Note that std::stoi will throw exception of type std::invalid_argument if the conversion cannot be performed, or std::out_of_range if the conversion results in overflow(i.e when the string value is too big for int type). You can use std::stol or std:stoll though in case int seems too small for the input string.

  • In C++03/98, any of the following can be used:

     std::string s = "10";
     int i;
    
     //approach one
     std::istringstream(s) >> i; //i is 10 after this
    
     //approach two
     sscanf(s.c_str(), "%d", &i); //i is 10 after this
    

Note that the above two approaches would fail for input s = "10jh". They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):

int to_int(char const *s)
{
     if ( s == NULL || *s == '\0' )
        throw std::invalid_argument("null or empty string argument");

     bool negate = (s[0] == '-');
     if ( *s == '+' || *s == '-' ) 
         ++s;

     if ( *s == '\0')
        throw std::invalid_argument("sign character only.");

     int result = 0;
     while(*s)
     {
          if ( *s < '0' || *s > '9' )
            throw std::invalid_argument("invalid input string");
          result = result * 10  - (*s - '0');  //assume negative number
          ++s;
     }
     return negate ? result : -result; //-result is positive!
} 

This solution is slightly modified version of my another solution.

怼怹恏 2024-10-15 02:12:09

您可以使用 boost::lexical_cast

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}

You can use boost::lexical_cast:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}
守不住的情 2024-10-15 02:12:09

您可以使用 istringstream

string s = "10";

// create an input stream with your string.
istringstream is(str);

int i;
// use is like an input stream
is >> i;

You can use istringstream.

string s = "10";

// create an input stream with your string.
istringstream is(str);

int i;
// use is like an input stream
is >> i;
小鸟爱天空丶 2024-10-15 02:12:09

没有“正确的方法”。如果您想要一个通用(但次优)的解决方案,您可以使用 boost::lexicalcast

C++ 的常见解决方案是使用 std::ostream<<运算符。您可以使用 stringstreamstringstream::str() 方法转换为字符串。

如果您确实需要快速机制(记住 20/80 规则),您可以寻找“专用”解决方案,例如 C++ 字符串工具包库

谨致问候,
马尔辛

There is no "right way". If you want a universal (but suboptimal) solution you can use a boost::lexical cast.

A common solution for C++ is to use std::ostream and << operator. You can use a stringstream and stringstream::str() method for conversion to string.

If you really require a fast mechanism (remember the 20/80 rule) you can look for a "dedicated" solution like C++ String Toolkit Library

Best Regards,
Marcin

瞄了个咪的 2024-10-15 02:12:09

一些方便的快速功能(如果您不使用 Boost):

template<typename T>
std::string ToString(const T& v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

template<typename T>
T FromString(const std::string& str)
{
    std::istringstream ss(str);
    T ret;
    ss >> ret;
    return ret;
}

示例:

int i = FromString<int>(s);
std::string str = ToString(i);

适用于任何可流类型(浮点数等)。您需要#include ,也可能需要#include

Some handy quick functions (if you're not using Boost):

template<typename T>
std::string ToString(const T& v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

template<typename T>
T FromString(const std::string& str)
{
    std::istringstream ss(str);
    T ret;
    ss >> ret;
    return ret;
}

Example:

int i = FromString<int>(s);
std::string str = ToString(i);

Works for any streamable types (floats etc). You'll need to #include <sstream> and possibly also #include <string>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文