【发布时间】: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