-3
#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str="ABC";
    int n=strlen(str);
    cout<<n;
}

This shows error which is:

error: cannot convert ‘std::string {aka std::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘size_t strlen(const char*)’
     int n=strlen(str);

But this works fine:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char str[]="ABC";
    int n=strlen(str);
    cout<<n;
}

What is the reason behind this?

Biffen
  • 5,354
  • 5
  • 27
  • 32
Aryan Adi
  • 11
  • 1
  • 7
    I'd recommend to stop guessing and instead get a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). And get rid of some bad habits like [`#inlcude `](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – churill Mar 10 '21 at 07:46

1 Answers1

2

strlen is a function that counts the nuber of characters between the memory adress specified by the const char* argument and the first \0. So you cannot pass a string as argument, since it does not represent any memory address. Instead use

str.size()

or (not efficient also not expected result if the string contains \0)

strlen(str.c_str()
limserhane
  • 884
  • 4
  • 13
  • It might be worth mentioning that `strlen` can work, but _might_ return a different result, because `std::string` is allowed to contain `'\0'` in the middle of the string. – churill Mar 10 '21 at 08:15
  • Yes you're right, I editted the post :) Thanks – limserhane Mar 10 '21 at 08:17