问题描述
如果有意义的话,我正在尝试使用 C++ 语法而不是 C 语法将我的基本 C 代码转换为 C++。但是,我有一个问题。我不知道如何在 C++ 中使用 strlen()
。在预处理中,我有 #include <iostream>
#include <string>
和 using namespace std;
。当我尝试编译时,它给出了以下错误消息:
error: use of undeclared identifier 'strlen'
int n = strlen(MessagetEnc);
和
error: use of undeclared identifier 'strlen'
for (int i = 0; i < strlen(MessagetEnc); i++)
此外,使用 #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];
}
}
我知道 C++ 不适合初学者,我只是想在阅读几篇文章后尝试一下,因为我打算在离开“初学者阶段”后完全学习它。
编辑:存在 std::
是因为我尝试去掉 using namespace std;
作为调试的一种方式。
解决方法
在 C++ 中有两种常见的字符串存储方式。旧的 C 风格方式,在这种情况下,您定义一个字符数组,customTSWorkerFactory
表示字符串的结尾。
\0
另一种定义字符串的方法是使用 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','o','\0'}
int len = strlen(str);
// To get the actual length you can use above function
。
std::string
,
strlen()
在 <string.h>
中声明,std::strlen()
在 <cstring>
中声明。无论哪种方式,它们都将 const char*
作为输入,而不是 std::string
。您必须使用 std::string::c_str()
来传递 C++ 字符串,例如:
#include <iostream>
#include <string>
#include <cstring>
int main ()
{
int EncCode;
std::cout << "Encryption code: " << std::endl;
std::cin >> EncCode;
std::string MessagetEnc;
std::cout << "Message to Encrypt:";
std::cin >> MessagetEnc;
std::cout << "Output: " << std::endl;
int n = std::strlen(MessagetEnc.c_str());
for (int i = 0; i < n; ++i)
{
std::cout << "Encrypted message" << MessagetEnc[i];
}
}
然而,完全没有必要对 C++ 字符串使用 (std::)strlen()
。改用 std::string::size()
方法,例如:
#include <iostream>
#include <string>
int main ()
{
int EncCode;
std::cout << "Encryption code: " << std::endl;
std::cin >> EncCode;
std::string MessagetEnc;
std::cout << "Message to Encrypt:";
std::cin >> MessagetEnc;
std::cout << "Output: " << std::endl;
size_t n = MessagetEnc.size();
for (size_t i = 0; i < n; ++i)
{
std::cout << "Encrypted message" << MessagetEnc[i];
}
}
可以通过使用 range-based for
loop 来进一步简化,例如:
#include <iostream>
#include <string>
int main ()
{
int EncCode;
std::cout << "Encryption code: " << std::endl;
std::cin >> EncCode;
std::string MessagetEnc;
std::cout << "Message to Encrypt:";
std::cin >> MessagetEnc;
std::cout << "Output: " << std::endl;
for (char ch : MessagetEnc)
{
std::cout << "Encrypted message" << ch;
}
}
,
尝试使用cstring头文件
在 c++ 中,strlen 类在 cstring 文件中。