【问题标题】:If input is NULL, return -1如果输入为 NULL,则返回 -1
【发布时间】:2017-11-15 01:22:37
【问题描述】:

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

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

旁注:如果您需要知道,这会将 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;

}

【问题讨论】:

  • 你为什么要使用指针?如果输入为nullptr,您的函数是否意味着执行某些操作?只需引用并强制调用者传递std::string
  • @Tas,您的建议非常好。不幸的是,CIS14 带有课堂作业的味道,所以这可能是一些缺乏实际经验的教育工作者的要求,或者我喜欢称之为C+ 程序员,一个从未完全接受从@987654326 过渡的程序员@ 到 C++ :-)

标签: c++ function pointers input null


【解决方案1】:

每次我将NULL 放入s 时,它都会崩溃。

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

为了防止在传递空字符串指针时发生这种情况:

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

你需要这样的东西作为你的函数中的 first 东西,试图取消引用 s:

if (s == nullptr)
    return -1

如果您陷入黑暗时代,请随意使用 NULL 而不是 nullptr :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    相关资源
    最近更新 更多