-3

atof(word)word はchar型です。単語が 3 や 2 などの数字の場合は機能しますが、単語が などの演算子の場合は atof は区別しません"+"。文字が数値かどうかを確認するより良い方法はありますか?

私はCSの初心者なので、これを適切に行う方法についてかなり混乱しています。

4

4 に答える 4

4

単一の をチェックする場合は、関数charを使用しisdigitます。

#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");
}

出力:

2 is digit: yes
+ is digit: no
a is digit: no
于 2016-02-12T20:26:06.950 に答える
4

はい、ありstrtol()ます。例

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"`.

この関数は、数字以外の文字が見つかったときに停止endptrし、元のポインターで数字以外の文字が表示された場所を指すようにするという考え方です。これは、「演算子」を非数値とは見なしません。これは、記号が数値の記号として使用されるため"+10"変換可能であるためです。2 つのオペランド間の「演算子」を解析する場合は、パーサーが必要です。単純なものでもかまいません。を使用して書かれている場合は、 のマニュアルをお読みください。10strpbrk(input, "+-*/")strpbrk()

于 2016-02-12T20:26:38.053 に答える
2

文字列に数字だけが含まれているということですか?

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

int main(void)
{
    char *str = "241";
    char *ptr = str;

    while (isdigit(*ptr)) ptr++;
    printf("str is %s number\n", (ptr > str) && (*str == 0) ? "a" : "not a");
    return 0;
}
于 2016-02-12T20:30:36.010 に答える
1

言葉で言えば、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() を使用してください

于 2016-02-13T09:08:00.480 に答える