Search code examples
c++strlen

How do I use 'strlen()' on a C++ string


I'm trying to convert my basic C code to C++ using the C++ syntax instead of C syntax, if that makes sense. However, I have a problem. I don't know how to use strlen() in C++. In preprocessing, I have #include <iostream> #include <string> and using namespace std;. When I try to compile, it gave the following error messages:

error: use of undeclared identifier 'strlen'
int n = strlen(MessagetEnc);

and

error: use of undeclared identifier 'strlen'
for (int i = 0; i < strlen(MessagetEnc); i++)

Also, using #include <cstring> doesn't seem to fix the problem.

This is the code:

#include <iostream>
#include <string>
using namespace std;
    
int main () 
{
    int EncCode; 
    std::cout << "Encryption code: " << std::endl;
    std::cin >> EncCode; 
    
    string MessagetEnc;
    std::cout << "Message to Encrypt:";
    std::cin >> MessagetEnc;
    std::cout << "Output: " << endl;
    
    int n = strlen(MessagetEnc);
    for (int i = 0; i < strlen(MessagetEnc); i++)
    {
        std::cout <<"Encrypted message" << MessagetEnc[i];
    }
}

I know C++ isn't beginner-friendly, I just wanted to try it after reading a few articles, as I plan to fully learn it after I leave the "beginner stage."

Edit: std:: is there because I tried getting rid of using namespace std; as a way to debug.


Solution

  • There are two common ways to store strings in C++. The old C-style way, in this case you define an array of characters and \0 indicates the end of the string.

    #include <cstring>
    
    char str[500] = "Hello";
    // How ever the capacity of str is 500, but the end of the actual string
    // must be indicated by zero (\0) within the str and Compiler puts it
    // automatically when you initialize it by a constant string.
    // This array contains {'H', 'e', 'l', 'l', 'o', '\0'}
    
    int len = std::strlen(str);
    // To get the actual length you can use above function
    

    Another way to define a string is to use std::string.

    #include <string>
    
    std::string str = "Hello";
    
    int len = str.size();
              ~~~~~~~~~~
    // or
    
    int len = str.length();
              ~~~~~~~~~~~~
    

    Footnote - You can carelessly use `std::strlen` on a `std::string` like this:
    std::string str = "Be careful!";
    int len = std::strlen(str.c_str());
    
    // Note: The pointer obtained from c_str() may only be treated as a pointer
    // to a null-terminated character string if the string object does not contain 
    // other null characters.
    

    Be careful, str.size() is not always equal to std::strlen(str.c_str())