如果输入为 NULL,则返回 -1
If input is NULL, return -1
代码工作正常,除了我需要添加这个约束。"如果输入为 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
:-(
相关文章:
- 如何在映射中返回null
- 为什么返回 NULL 不会破坏函数?
- fopen 在 gdb 中返回 NULL
- 为什么要从main()返回NULL?
- 为什么TinyXML2的XMLDocument::FirstChild()函数在尝试解析这个有效的XML文件时返回NULL?
- Box2D World.GetBodyList() 返回 NULL,但 World 显然正在更新对象
- boost::p ython:PyErr_Fetch始终返回 NULL 回溯
- 如何在 Visual C++ 中从返回类型为 map 的函数返回 null?
- 如何在C++中返回Null作为引用
- 从模板化函数返回Null对象
- GDALOpen 在 GEOTiff 文件上返回 null
- PyThreadState_GET() 从 PyImport_GetModuleDict() 中返回 NULL
- (位图)LoadImage() 返回 NULL,GetLastError() 返回 0
- 在构造函数处将类对象强制转换为接口始终返回 NULL
- 如何为迭代器返回"null"值?
- 具有 4 个指针的节点的递归插入函数返回 null
- winAPI FindResource 仅在 DLL 中返回 NULL
- 使用 dlopen/dlsym 打开C++共享库 - dlsym 返回 NULL
- SetWindowsHookEx 在挂接到其他线程时返回 NULL
- 尚未归shared_ptr所有的实例的 shared_from_this() 总是返回 null?