How do you check if a char is a number in c?

时间:2016-02-12 20:24:44

标签: c char atof

I'm using a.directive("directOne", function ($templateRequest, $compile, $controller) { return { //controller: 'oneController', link: function (scope, elem, attrs) { $templateRequest("template.html").then(function (html) { var $scope = scope.$new(); //stored oneController scope in variable var controllerScope = $controller('oneController', {$scope, $scope}); var template = angular.element(html); $(elem).append(template); template = $compile(template)(controllerScope); //compiled with oneController scope }); } }; }); , where word is a atof(word) type. It works when the word is a number, such as 3 or 2, but atof doesn't distinguish when word is an operator, such as char. Is there a better way to check whether the char is a number?

I'm a newbie to CS, so I'm quite confused on how to do this properly.

4 个答案:

答案 0 :(得分:2)

If you're checking a single enum ModalTypes { Add, Edit } public openManageModal(type: ModalTypes) { if (type == ModalTypes.Add) { //Open edit modal } else { //Open add modal } } , use the char function.

isdigit

Output:

#include <stdio.h>
#include <ctype.h>

int main()
{
    printf("2 is digit: %s\n", isdigit('2') ? "yes" : "no");
    printf("+ is digit: %s\n", isdigit('+') ? "yes" : "no");
    printf("a is digit: %s\n", isdigit('a') ? "yes" : "no");
}

答案 1 :(得分:2)

Yes there is, .To<SomeViewModel>(). Example

strtol()

The above would print char *endptr; const char *input = "32xaxax"; int value = strtol(input, &endptr, 10); if (*endptr != '\0') fprintf(stderr, "`%s' are not numbers\n"); xaxax' are not numbers"`.

The idea is that this function stops when it finds any non numeric character, and makes " point to the place where the non numeric character appeared in the original pointer. This will not consider and "operator" as a non numeric value because endptr is convertible to "+10" since the sign is used as the sign of the number, if you want to parse the "operator" between two operands you need a parser, a simple one could be written using 10, read the manual for strpbrk(input, "+-*/").

答案 2 :(得分:2)

Do you mean if a string contains only digits?

contrasts(treat) <- cbind(c(0,1,0),c(0,0,1))
Treat <- model.matrix(~ treat)[, -1]

答案 3 :(得分:0)

假设用词来表示一个字符串,在C中,它是char *或char []。

我个人会使用atoi()

This function returns the converted integral number as an int value. If no valid conversion could be performed, it returns zero.

示例:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void is_number(char*);

int main(void) {
    char* test1 = "12";
    char* test2 = "I'm not a number";

    is_number(test1);
    is_number(test2);
    return 0;
}

void is_number(char* input){
    if (atoi(input)!=0){
        printf("%s: is a number\n", input);
    }
    else
    {
        printf("%s: is not a number\n", input);
    }
    return;
}

输出:

12: is a number
I'm not a number: is not a number

但是,如果你只是检查一个字符,那么只需使用isdigit()