【问题标题】:int strlen has zero stored in it c++int strlen 中存储了零 c++
【发布时间】:2022-01-23 04:32:51
【问题描述】:

我尝试 strlen for char 以获取 cstring 中的多少个字符以加入一个在代码中查找字符的循环,但 strlen 只返回 0 电子邮件 [] 我将其设为空以获取其中的任何值

using namespace std;
#include <iostream>
#include <cstring>
int main(int argc, char **argv)


{
char email[] = "";

cout << "Enter the email in question"<< endl;
cin >> email;

int size = strlen(email);

for (int i = 0; i < size; i++)
{
    cout << email;
    if (email[i] == '@' )
    {
        cout << "valid email";
}
    
}

【问题讨论】:

  • char email[] = ""; 定义了一个大小正好存储空终止符的数组。您无法在此字符串中读取任何有用的内容。
  • 为什么不使用std::string
  • 您将char email [] 视为std::string。如果您确实将其更改为std::string,那么所有其他代码都可以工作(strlen 除外——您将使用size())。
  • 您的程序有未定义的行为,通常无法预测具体会发生什么以及为什么会发生。
  • 假设必须在没有std::string 的情况下完成分配,char email[20] 将允许您将 19 个字符读入此字符串(永远不要忘记空终止符!),但 cin &gt;&gt; email; 不知道如何大数组是(请参阅array decay),并且会很高兴地读取数组的末尾并将您放在类似的船上。你想使用一些允许你指定数组长度的东西,比如cin.getline(email, sizeof(email));

标签: c++ c-strings


【解决方案1】:
char email[] = "";

这是一个空字符串。字符串的长度为0,数组的大小为1。唯一的元素是空终止符。

但是 strlen 只返回 0

这并不奇怪,因为唯一可以放入数组的字符串是长度为 0 的字符串。

cin >> email;

在 C++ 20 之前,此语句曾经非常不安全。如果您要提供比数组大小更长的输入,那么您会溢出数组。由于数组的大小为 1,因此唯一适合的字符串是空字符串,因此任何非空输入都会溢出。

数组溢出将导致未定义的行为。因此,您观察到的行为将无法得到保证。这是不好的;不要这样做。

从 C++20 开始,运算符将安全地只读取数组中适合的字符数,并考虑空终止符 - 在本例中为 0 个字符。这是安全的,但可能不是您想要的。

一个好的解决方案是使用std::string:

std::string email;
std::cin >> email;
int size = email.size();

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2023-02-02
    • 2019-02-23
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2014-06-12
    • 2023-01-03
    相关资源
    最近更新 更多