1

文字配列を動的に入力し、含まれている値が有効な整数であるかどうかを確認したいのですが、これまでに得たものは次のとおりです。

for(int i = 0; i < 50000; i++)
    {
        if(input[i] == ',')
        {
            commaIndex = i;
        }
    }

commaIndex はファイル内のコンマのインデックスです。数値はコンマの前に入力する必要があります。ファイルは次のようになります: -44,5,19,-3,13,(etc), この部分で重要です:

char *tempNumber = new char[commaIndex];

tempNumber を入力します (おそらく、動的割り当てのために数値と同じ大きさになるはずです)。そのため、サイズ 50000 の文字配列 (名前付き入力) に数値がありません。

for(int i = 0; i < commaIndex; i++)
    {
            cout << i << "\n";
            tempNumber[i] = input[i];
    }

そして今、私はそれを使いたい:

if(!isValidInteger(tempNumber))
    {
        cout << "ERROR!\n";
    }

残念ながら、「commaIndex」の値に関係なく、tempNumber は常にサイズ 4 のようです。つまり、次の出力が得られます。

(入力データ: 50000,3,-4)

commaIndex: 5 tempNumber: 5000 の内容 (0 が 1 つ欠落)

commaIndex: tempNumber の 1 コンテンツ: 3²²² (3 つの ^2 に注意してください)

commaIndex: 2 tempNumber の内容: -4²²

何か案は?

もう 1 つ: これは宿題のためのものであり、C++ のオブジェクト指向要素を使用することは許可されていません (これには文字列とベクトルが含まれます。私はそこに行ったことがあり、とても簡単であることはわかっています)。

ありがとう、

デニス

4

2 に答える 2

1

strtok()との使用を検討することもできますsscanf()。解析エラーでstrtol()(完全に有効な)値を返すだけなので、エラーをチェックできないことに注意してください。0一方、sscanf()正常に読み取られたアイテムの数を返すため、数値の読み取り中にエラーが発生したかどうかを簡単に確認できます。

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

int main()
{
    int i = 0;
    char str[] = "1,2,-3,+4,a6,6";

    /* calculate result table size and alloc */
    int max = 1;
    char* tmp = str;
    while (*tmp)
        if (*tmp++ == ',')
            ++max;

    int* nums = malloc(sizeof(int) * max);

    /* tokenize string by , and extract numbers */
    char* pch = strtok(str, ",");
    while (pch != NULL) {
        if (sscanf(pch, "%d", &nums[i++]) == 0)
            printf("Not a number: %s\n", pch);
        pch = strtok(NULL, ",");
    }

    /* print read numbers */
    for (i = 0; i < max; ++i)
        printf("%d\n", nums[i]);

    free(nums);

    return 0;
}
于 2012-11-08T14:21:16.843 に答える
1

strtol関数に興味があるかもしれません。

于 2012-11-08T13:31:29.227 に答える