c++ - 如何处理从 main 接收到的 NULL。 C++

标签 c++ function null

我是 C++ 新手。我有一个名为 isValid(const char str[]);

的函数
int isValid (const char str[])
{
  int len = strlen (str);

  if (strlen (str) != 10)
     return 0;
  if (!isdigit (str[i]))
     return 0;
  if (str==NULL)
     return 0;
  if (atol(str)==1234567890)
     return 1;
}

样本主:

int main(void)
{
   char test[10];
   cout<<"Testing NULL"<<endl;
   cout<< isValid(NULL)<<endl;

   cout<<"Testing isValid"<<endl<<"Enter test: ";
   cin>>test;
   cout<<isValid(test)<<endl;
   return 0;
}

我得到这个:

Testing NULL

Segmentation fault

我如何实现 NULL。 谢谢!

最佳答案

isValid 中的测试顺序错误 - 您需要先测试 NULL,然后再调用 strlen 或取消引用 str.

你还有另外几个错误:

isValid 需要为您的 if 条件都不满足的情况添加一个返回值。我原以为这会产生警告。如果没有,在启用警告的情况下进行编译(/W4 对于 MSVC,-Wall 对于 gcc)会标记它。

i 未定义,因此 isdigit(str[i]) 无法编译。我更新的代码(下方)显示了如何确认 str 中的每个字符都是数字

int isValid (const char str[])
{
    if (str==NULL)
        return 0;
    size_t len = strlen(str);
    if (len != 10)
        return 0;
    for (size_t i=0; i<len; i++) {
        if (!isdigit (str[i]))
            return 0;
    }
    if (atol(str)==1234567890)
        return 1;
    return 0;
}

关于c++ - 如何处理从 main 接收到的 NULL。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884779/

相关文章:

c++ - 如何使用if else语句

c - C 中的函数是否有 "type name"?

javascript - addClass(undefined) 与 addClass(null)

c++ - 在 c++ 函数中访问 objective-c 类的 ivars

c++ - 链接 Qt5.6 会产生找不到所需引用的错误

c++ - 参数是对文字类型的引用时的常量函数

c - 函数参数名称是否在 C 的内存中占有一席之地?

matlab - 矩阵作为Matlab函数的输入输出

php - PHP 中的 MySQL NULL

forms - 删除来自空集合表单项的空值