【问题标题】:Convert C++ string variable to long将 C++ 字符串变量转换为 long
【发布时间】:2012-08-02 11:09:51
【问题描述】:

我有一个变量:

string item;

它在运行时被初始化。我需要将其转换为长。怎么做?我试过 atol() 和 strtol() 但我总是分别得到以下错误 strtol() 和 atol():

cannot convert 'std::string' to 'const char*' for argument '1' to 'long int strtol(const char*, char**, int)'

cannot convert 'std::string' to 'const char*' for argument '1' to 'long int atol(const char*)'

【问题讨论】:

  • string 有一个函数 c_str 会将其公开为 const char*
  • item.c_str() 将返回const char* 中的std::string。

标签: c++ string long-integer


【解决方案1】:

c++11:

long l = std::stol(item);

http://en.cppreference.com/w/cpp/string/basic_string/stol

C++98:

char * pEnd;.
long l = std::strtol(item.c_str(),&pEnd,10);

http://en.cppreference.com/w/cpp/string/byte/strtol

【讨论】:

  • 值得一提的是C++11,所以你需要检查你有一个最新的编译器,以及要使用哪些标志。
  • -1 for long l = atol(item.c_str()); 因为这个函数不安全!
  • @Nawaz:“不安全”有点夸张。它不允许您检查输入是否真的是数字字符串;这是否“安全”取决于它来自哪里以及你正在用它做什么。
  • 如果发生错误,对atol 的记录调用会导致未定义的行为。
  • @Nawaz 这就是为什么我在执行此类操作之前检查以确保我的字符串是有效数字的原因。但如果我这样做,它仍然“不安全”吗?
【解决方案2】:

试试这样:

long i = atol(item.c_str());

【讨论】:

  • 谢谢!我不知道需要使用 c_str() 将 C++ 字符串转换为 char*
  • -1 for long i = atol(item.c_str()); 因为这个函数不安全!
  • @tenfour:试试这个:cout << atoi("9879abc879xyz"); 看看它打印了什么!
  • 我想我们对“不安全”的含义有不同的看法。这只是古怪的行为,在很多情况下甚至是首选。显然,atol 距离成为一个很好的答案还有 3-4 个级别,但“不安全”似乎有些夸张。
  • @tenfour:这是不安全的,因为它没有告诉你它没有真的转换整个字符串,并且没有' t告诉你问题。这是不安全的,因为它不会告诉你这两个调用之间的区别:atoi("0") 和 atoi("abc")。 Both return 0。 :P
【解决方案3】:

使用字符串流。

#include <sstream>

// code...
std::string text;
std::stringstream buffer(text);
long var;
buffer >> var;

【讨论】:

    【解决方案4】:

    使用std::stol

    【讨论】:

      【解决方案5】:

      如果你没有 C++11 的访问权限,而你可以使用 boost 库,你可以考虑这个选项:

      long l = boost::lexical_cast< long >( item );
      

      【讨论】:

        猜你喜欢
        • 2016-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-02
        • 2019-06-21
        • 2015-10-25
        相关资源
        最近更新 更多