2012-11-08 35 views
1

我希望動態填充字符數組,並檢查所包含的值是否有效整數值,這裏就是我有這麼遠:填充動態大小的數組在C++和使用

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

commaIndex是文件內部逗號的索引,數值應該在逗號前輸入,文件如下所示:-44,5,19,-3,13,(等),這部分很重要:

char *tempNumber = new char[commaIndex]; 

填充tempNumber(它應該大概與我的動態分配一樣大),所以我沒有數字r大小爲50000 char-array(命名輸入)。

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

,現在我想使用它:

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

不幸的是,tempNumber似乎總是「commaIndex」的值的大小4 irregardless的,即我得到以下的輸出:

(Inputdata:50000,3,-4)

commaIndex:5 內容tempNumber的:5000(一個0缺失)

commaIndex:tempNumber 1分 含量:3²²²(注意3^2S)

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

任何想法?

還有一件事:這是一個家庭作業的作業,我不允許使用任何面向對象的C++元素(這包括字符串和向量,我一直在那裏,我知道它會是SO簡單。)

感謝,

丹尼斯

+0

'的std ::矢量' – Xeo

+0

我也不允許使用,不幸的是,我去過那兒。我會相應地更新我的問題。 –

+3

打你的老師,這只是愚蠢的。當*爲了學習的目的而重新實現時,你只應該不允許使用'std :: vector'和類似的東西*。 – Xeo

回答

1

您可能會感興趣由strtol功能。

+0

是的,我可能是,我已經是,但我忘了補充:這是爲了做家庭作業,我不允許爲此使用字符串或任何面向對象的C++實現。感謝您的提示! –

+0

請注意,'strtol'不使用'std :: string',而是包裝同名的標準C函數。 –

+1

@DennisRöttger這意味着你在問C而不是C++。 – Archie

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; 
}