如何编写自己的 isnumber() 函数? [英] How to write own isnumber() function?

查看:35
本文介绍了如何编写自己的 isnumber() 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 新手,我正在考虑如何自己编写这个函数.我从命令行获取一个参数,所以它存储在 argv 数组中,我想决定它是否是数字.最简单的方法是什么?

I'm new to C and I'm thinking how to write this function myself. I take a parameter from command line, so it is stored in argv array and I want to decide whether it is or isn't number. What is the easiest way to do this?

谢谢

#include <stdio.h>

int isNumber(int *param)
{   
    if (*param > 0 && *param < 128)
        return 1;
    return 0;
} 

int main(int argc, char *argv[])
{
    if (argc == 2)
        isNumber(argv[1]);
    else printf("Not enought parameters.");

    return 0;
}

推荐答案

阅读strtol(3).你可以把它当作

bool isnumber(const char*s) {
   char* e = NULL;
   (void) strtol(s, &e, 0);
   return e != NULL && *e == (char)0;
}

但这不是很有效(例如,对于一百万位数的字符串),因为会进行无用的转换.

but that is not very efficient (e.g. for a string with a million of digits) since the useless conversion will be made.

但实际上,你经常关心那个数字的值,所以你会在你的程序参数处理中调用strtol(argv参数到main) 并关心 strtol 的结果,即数字的实际值.

But in fact, you often care about the value of that number, so you would call strtol in your program argument processing (of argv argument to main) and care about the result of strtol that is the actual value of the number.

您使用 strtol 可以更新(通过它的第三个参数)一个指向解析字符串中数字末尾的指针的事实.如果该结束指针没有成为字符串的结尾,则转换以某种方式失败.

You use the fact that strtol can update (thru its third argument) a pointer to the end of the number in the parsed string. If that end pointer does not become the end of the string the conversion somehow failed.

例如

int main (int argc, char**argv) {
   long num = 0;
   char* endp = NULL;
   if (argc < 2) 
     { fprintf(stderr, "missing program argument\n");
       exit (EXIT_FAILURE); }; 
   num = strtol (argv[1], endp);
   if (endp == NULL || *endp != (char)0)
     { fprintf(stderr, "program argument %s is bad number\n", argv[1]);
       exit (EXIT_FAILURE); }; 
   if (num<0 || num>=128)
     { fprintf(stderr, "number %ld is out of bounds.\n", num);
       exit(EXIT_FAILURE); };
   do_something_with_number (num);
   exit (EXIT_SUCCESS);
 } 

这篇关于如何编写自己的 isnumber() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆