如果输入为 NULL,则返回 -1

If input is NULL, return -1

本文关键字:返回 NULL 输入 如果      更新时间:2023-10-16

代码工作正常,除了我需要添加这个约束。"如果输入为 NULL,则返回 -1"。

只是想知道我该怎么做。每次我为 s 输入 NULL 时,它都会崩溃。

旁注:如果您需要知道,这会将 excel 标题转换为数字,例如 A = 1、Z = 26、AA = 27、AB = 28 等。

#include <iostream>
using namespace std;
class CIS14
{
public:
int convertExcelTitleToNumber(string* s)
{
    string str = *s;
    int num = 0;
    for (unsigned int i = 0; i < str.length(); i++)
    {
        num = num * 26 + str[i] - 64;
    }
    return num;
}
};
int main()
{
CIS14 cis14;
string s = "AA";
cout << cis14.convertExcelTitleToNumber(&s) << endl;
return 0;

}

每次我把NULL放进去s,它都会崩溃。

这并不让我感到惊讶,取消引用空指针(在您的情况下带有string str = *s(是未定义的行为。

若要在传递空字符串指针时防止出现这种情况,请执行以下操作:

cout << cis14.convertExcelTitleToNumber(nullptr) << endl;

尝试取消引用之前,您需要这样的东西作为函数中的一件事s

if (s == nullptr)
    return -1

如果您被困在黑暗时代,请随意使用 NULL 而不是nullptr:-(