-5

so i just want to convert int in digits and store it in array

for eg

int n=456;

std::string nstr = std::to_string(n);

std::cout << nstr[0];

now i just want the length of nstr...

whenever i am using std::strlen(nstr);

its giving an error

**error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'**

please tell me how to convert std::__cxx11::string to std::string

or is there any other way to calculate length of nstr

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    Why use `strlen()` instead of `std::string::size()`? – Fred Larson Dec 03 '19 at 14:09
  • `strlen` is for character arrays, you can just use `nstr..size()` – Alan Birtles Dec 03 '19 at 14:09
  • 1
    `std::string` has a `size` and `length` member functions that do this for you. `strlen` is for c-strings, not `std::string`s – NathanOliver Dec 03 '19 at 14:09
  • You can convert a `std::string` to `const char*` with `c_str()` as shown [here](https://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char). – Tony Tannous Dec 03 '19 at 14:13
  • 2
    Not only is using `strlen()` not correct, A call to `strlen()` is an `O(n)` operation, where `n` is the number of characters (including) the terminating null. A call to `size()` is an `O(1)` operation, since a `std::string` knows the number of characters stored without having to look for a null. So even if you got your code to work with `strlen`, it is slower than using `size`. – PaulMcKenzie Dec 03 '19 at 14:18
  • 3
    `std::__cxx11::string` _is_ `std::string`. Your error is clearly about converting to `const char*`, not about converting to `std::string`, so I don't understand why you ask about the latter in the question title and body... – Max Langhof Dec 03 '19 at 14:23

2 Answers2

2

hot to convert std::__cxx11::string to std::string

std::__cxx11::string is (a name of) std::string in the standard library implementation that you use.

std::string cannot be passed to std::strlen, because it requires the argument to be const char* instead, as explained in the error message.

or is there any other way to calculate length of nstr

Typically, you should use the size member function. No calculation is involved however. The size was calculated when the string was created, and then stored within the string object.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

If you really, really, really want to use strlen(), you have to convert to char*:

std::strlen(nstr.c_str());

But usually you would just ask the string for its size:

nstr.size();

The only reason I can think of you might prefer strlen() is if you have embedded nulls in your string, and you want to stop your count there.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174