【问题标题】:c++ error: cannot convert basic_string<char>}' to 'const char*' for argument '1' to 'long int strtolc++ 错误:无法将参数 '1' 的 basic_string<char>}' 转换为 'const char*' 到 'long int strtol
【发布时间】:2017-08-02 05:56:16
【问题描述】:

我是 C++ 新手,不过我已经用 C 编程了一段时间。 尝试读入一个字符串,然后使用 strtol 将字符串转换为 int。 我正在使用 gcc 编译器。 我收到以下错误消息:“c++ error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'const char*' for argument '1' to 'long int strtol( const char*, char**, int)' int c = strtol(str[j], &p, 10);". 我尝试了不同类型的转换,但我非常喜欢 strtol 以供将来参考。我的向量字符串有什么关系吗?

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;
using std::string;

int main()
{
  int a = 0;
  int i = 0;
  int size = 0;
  int* big;

  cin>>a;
  size = a*2;

  int sizes[size];
  string *str = new string[size];
  while(i < a){
    cin>>str[i];
  i++;
}

i = 0;
while(i < a){
  cout << str[i] << endl; // just for checking
  i++;
}



for (int j =0; j<size-1;j++){
  char* p;
  char* q;
  int c = strtol(str[j], &p, 10);
  if (!*p) {
     sizes[j] = *p;
  }else{
     sizes[j] = *p/2;
  }
}

return 0;
}

提前致谢!

【问题讨论】:

标签: c++ string c++11


【解决方案1】:

您可以使用strtol(str[j].c_str(), &amp;p, 10);对c_str() 的调用返回指向字符串对象内容的const char*,而strtol 需要const char*。或者你可以写更多地道的代码,然后调用std::stol(str[j])。

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多