c ++从字符串解析int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4442658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:25:28  来源:igfitidea点击:

c++ parse int from string

c++stringint

提问by kralco626

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

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

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.

我做了一些研究,有些人说要使用 atio,有些人说它很糟糕,无论如何我都无法让它发挥作用。

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

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

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

Thanks!

谢谢!

回答by Nawaz

  • In C++11, use std::stoias:

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

    Note that std::stoiwill throw exception of type std::invalid_argumentif the conversion cannot be performed, or std::out_of_rangeif the conversion results in overflow(i.e when the string value is too big for inttype). You can use std::stolor std:stollthough in case intseems 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
    
  • 在 C++11 中,std::stoi用作:

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

    请注意,如果无法执行转换,或者如果转换导致溢出(即当字符串值对于类型来说太大时),std::stoi将抛出类型异常。您可以使用or以防输入字符串看起来太小。std::invalid_argumentstd::out_of_rangeintstd::stolstd:stollint

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

    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):

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

int to_int(char const *s)
{
     if ( s == NULL || *s == '
#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;
}
' ) throw std::invalid_argument("null or empty string argument"); bool negate = (s[0] == '-'); ? ? ?if ( *s == '+' || *s == '-' )? ? ? ? ? ++s; if ( *s == '
string s = "10";

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

int i;
// use is like an input stream
is >> i;
') throw std::invalid_argument("sign character only."); ? ? ?int result = 0; ? ? ?while(*s) ? ? ?{ ? ? ? ? ? if ( *s >= '0' && *s <= '9' ) ? ? ? ? ? { ? ? ? ? ? ? ? result = result * 10 ?- (*s - '0'); ?//assume negative number ? ? ? ? ? } ? ? ? ? ? else ? ? ? ? ? ? ? throw std::invalid_argument("invalid input string"); ? ? ? ? ? ++s; ? ? ?} ? ? ?return negate ? result : -result; //-result is positive! }?

This solution is slightly modified version of my another solution.

此解决方案是我的另一个解决方案的略微修改版本。

回答by Eugen Constantin Dinca

You can use boost::lexical_cast:

您可以使用boost::lexical_cast

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;
}

回答by Marcin

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

没有“正确的方法”。如果您想要一个通用(但次优)的解决方案,您可以使用 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.

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

If you really require a fast mechanism (remember the 20/80 rule) you can look for a "dedicated" solution like http://www.partow.net/programming/strtk/index.html

如果您确实需要快速机制(请记住 20/80 规则),您可以寻找“专用”解决方案,例如http://www.partow.net/programming/strtk/index.html

Best Regards,
Marcin

最好的问候,
Marcin

回答by Sanjit Saluja

You can use istringstream.

您可以使用istringstream

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

回答by AshleysBrain

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

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

##代码##

Example:

例子:

##代码##

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

适用于任何可流式传输类型(浮点数等)。您需要#include <sstream>并且可能还需要#include <string>