"strlen()" works with literal but not string type variable

Asked

Viewed 68 times

2

I have this code:

#include <iostream>
#include <string.h>
using namespace std;

int main() {
   int len = strlen("Teste");
   cout << len << endl;
   
   return 0;
}

That generates the output:

5

In the code above, I was using the function strlen() in C++ to count the number of characters in the string "Teste". So far so good, but when I create a variable like string:

#include <iostream>
#include <string.h>
using namespace std;

int main() {
   string nome = "Teste";
   int len = strlen(nome);
   
   cout << len << endl;
   
   return 0;
}

The program gives error. Why? The function strlen() does not accept variables? So I went there and tried otherwise, I changed the type of variable to type char, then the code went like this:

#include <iostream>
#include <string.h>
using namespace std;

int main() {
   char nome[10] = "Teste";
   int len = strlen(nome);
   
   cout << len << endl;
   
   return 0;
}

And this time it worked, he returned the number of characters of the word, but I ask, char nome[10] = "Teste"; is not the same thing as string nome = "Teste";? Why didn’t it work with the type variable string?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

5

"Teste" by default is a type char *, is not a guy string. I mean, it’s C’s way of creating a string, is not the form of C++. And if you will use the form of C then the strlen(), which is a C function (exists in C++ by compatibility, unused, but usually not the most suitable), works. strlen() expecting a char *, not a string.

The third way is that same kind, only allocating in the stack as a array.

If you declare something to be string then you must use what this guy offers, and the correct one which is the length() in the object itself.

So if you say the guy is string has to ask for the size, which is even absurdly more efficient than the form of C. Correctly:

#include <iostream>
#include <string>
using namespace std;

int main(){
   string nome = "Teste";
   cout << nome.length() << endl;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Just out of curiosity (and to keep registered), unlike the function strlen, which is linear, the method length is constant?

  • 1

    Yeah, that’s something that makes the strlen() a walking bomb.

  • 1

    @Luizfelipe https://answall.com/q/167528/112052 | https://www.joelonsoftware.com/2001/12/11/back-to-basics/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.