0

I'm new to C++, been programming a while in C though. Trying to read in a string and then convert the string into int by using strtol. Iam using the gcc compiler. And I get the following error message: "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);". I have tried different types of conversions but really like the strtol for future reference. Is there something to do with my vector string?

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

Thanks in advance!

Borgleader
  • 15,826
  • 5
  • 46
  • 62
  • 1
    Can you reduce the code to whats causing the error? Or at least mention which line it is? – Borgleader Mar 12 '17 at 02:11
  • 1
    `int sizes[size];` is not standard C++, this is an extension which means this code is not portable. Also `using std::string;` is rendundant when you also have `using namespace std;`. Also you never delete `string *str = new string[size];` (which you should, although an ever better solution would be `std::vector`) – Borgleader Mar 12 '17 at 02:16
  • Possible duplicate of [cannot convert 'std::basic\_string' to 'const char\*' for argument '1' to 'int system(const char\*)'](http://stackoverflow.com/questions/21589353/cannot-convert-stdbasic-stringchar-to-const-char-for-argument-1-to-i) – Raymond Chen Mar 12 '17 at 04:18

1 Answers1

1

You can use strtol(str[j].c_str(), &p, 10); the call to c_str() returns a const char* that points at the contents of the string object, and strtol wants a const char*. Or you can write more idiomatic code, and call std::stol(str[j]).

Pete Becker
  • 74,985
  • 8
  • 76
  • 165