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)

commaIndex: 1 tempNumber 的内容: 3²²² (注意 3 ^2s)

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

有任何想法吗?

还有一件事:这是一个家庭作业,我不允许使用 C++ 的任何面向对象的元素(这包括字符串和向量,我去过那里,我知道这很容易。)

谢谢,

丹尼斯

4

2 回答 2

1

您可能对strtol函数感兴趣。

于 2012-11-08T13:31:29.227 回答
1

您也可以考虑使用strtok()with 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 回答