如何在 C++ 字符串上使用“strlen()”

Ani*_*que 4 c++ strlen

我正在尝试使用 C++ 语法而不是 C 语法将我的基本 C 代码转换为 C++,如果这有意义的话。但是,我有一个问题。我不知道如何strlen()在C++中使用。在预处理中,我有#include <iostream> #include <string>using namespace std;。当我尝试编译时,出现以下错误消息:

error: use of undeclared identifier 'strlen'
int n = strlen(MessagetEnc);
Run Code Online (Sandbox Code Playgroud)

error: use of undeclared identifier 'strlen'
for (int i = 0; i < strlen(MessagetEnc); i++)
Run Code Online (Sandbox Code Playgroud)

此外,使用#include <cstring>似乎并不能解决问题。

这是代码:

#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];
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道C++不太适合初学者,我只是想在读了几篇文章后尝试一下,因为我打算在离开“初学者阶段”后全面学习它。

编辑:std::是因为我尝试摆脱using namespace std;作为调试的方式。

mas*_*oud 7

C++ 中有两种常见的存储字符串的方法。旧的 C 风格方式,在本例中定义一个字符数组并\0指示字符串的结尾。

#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
Run Code Online (Sandbox Code Playgroud)

定义字符串的另一种方法是使用std::string.

#include <string>

std::string str = "Hello";

int len = str.size();
          ~~~~~~~~~~
// or

int len = str.length();
          ~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
脚注 - 您可以不小心在 `std::string` 上使用 `std::strlen`,如下所示:
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.
Run Code Online (Sandbox Code Playgroud)

小心,str.size()并不总是等于std::strlen(str.c_str())