2012-02-11 71 views
0

如何保存數組中的文本文件中的所有數字?例如:如何從文件中讀取數字字符串並將其放入數組中?

我叫亨利,今年19歲。我出生於1992年。5ro2k。

該程序應該從文件中讀取19,1992,5,2號碼並將它們保存在一個數組中。如果單詞是52rok,那麼它應該讀取數字52.

+0

不是*確切*重複,但[我對前一個問題的回答](http://stackoverflow.com/a/3096245/179910)仍然涵蓋了這個很好。 – 2012-02-11 04:57:41

+0

一些快速指導。編寫代碼「打開」文件,逐行讀取,使用atoi將字符串轉換爲int。並將int保存在數組中。令人印象深刻的19歲,並開始提出問題stackoverflow。保持它,但不斷提高你的質量問題。不要放棄。 – Siddharth 2012-02-11 05:10:39

+0

@MichaelPetrotta我被困在如何閱讀值和什麼條件給予獲得數值。我知道如何讀文件的唯一方法是通過'getc()'' 'void main \t char ch; ary [100],i; \t fp = fopen(argv [1],「r」); \t而(!(CH = GETC(FP))= EOF) \t { \t \t 「一些條件來檢查數字」 進制(I)= CH; i ++; \t} \t fclose(fp); }' – 2012-02-11 08:25:37

回答

2

一種方法是用空格替換除數字以外的所有字符,並使用strtok標記所得到的字符串。

這是一個骯髒的pseudocodish例如,你可以修改,以適應您的需求:

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

int main() { 
    char s[] = "My name is Henry, I am 19 years old. I was born in 1992. 5ro2k."; 
    char *p = s; 
    while (*p) { 
     if (!isdigit(*p)) { 
      *p = ' '; 
     } 
     p++; 
    } 
    p = strtok(s, " "); 
    while (p) { 
     printf("%s\n", p); 
     p = strtok(NULL, " "); 
    } 
} 

主要的東西,它使這個例子髒是使用strtok,這不是線程安全的。您應該使用strtok_r。當然,你需要自己解析整數的字符串(atoi是個不錯的選擇)。

相關問題