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!

3
  • 1
    Can you reduce the code to whats causing the error? Or at least mention which line it is? Commented Mar 12, 2017 at 2: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) Commented Mar 12, 2017 at 2:16
  • Possible duplicate of cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' Commented Mar 12, 2017 at 4:18

1 Answer 1

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]).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.