2014-02-12 19 views
0
int main(void) 
{ 
int i,j=0,k;        //initialization 
char equation[100];       //input is a string (I think?) 
int data[3];         //want only 3 numbers to be harvested 

printf("Enter an equation: "); 
fgets(equation, 100, stdin);    //not so sure about fgets() 

for (i = 0; i < equation[100]+1; i++) {   //main loop which combs through 
                //"equation" array and attempts 
                //to find int values and store 
    while (j <= 2) {        //them in "data" array 
     if (isdigit(equation[i])) { 
      data[j] = equation[i] 
      j++; 
     } 
    } 
    if (j == 2) break; 

} 

for (k = 0; k <= 2; k++) {     //this is just to print the results 
    printf("%d\n", data[k]); 
} 

return 0; 
} 

Hello!這是我在C語言中的入門級程序,我試圖梳理一個數組,並將這些數字取出並分配給另一個數組,然後我可以訪問和處理這些數組。嵌套for/while循環和數組,從數組中濾除數字

但是,每當我運行這個我得到0 0 0作爲我的三個元素在我的「數據」數組。

我不確定我是否對自己的邏輯或數組語法犯了錯誤,因爲我是數組的新手。

在此先感謝! :)

+0

你不想要的0陣列中? – Mozzie

+0

那麼,除非輸入字符串是0 0 0!我總是得到0 0 0而不是實際的字符串:( – ZumbaLover69

+0

這個「for(i = 0; i

回答

0

有代碼中的幾個問題:

  1. for (i = 0; i < equation[100]+1; i++) {應該像

    size_t equ_len = strlen(equation); 
    for (i = 0; i < equ_len; i++) { 
    

    無論輸入的equation[100]的價值是不確定的,因爲char equation[100];equation只有100個元素,最後一個是equation[99]

  2. equation[i] = data[j];應該

    data[j] = equation[i]; 
    

    要在equation存儲數字到data我想。

  3. break;應該被刪除。

    break;語句將跳出while循環,其結果是,你會在equation最後一位數字存儲data[0](假設你已經切換dataequation,在#2中指出)。

    如果你想在equation前三位,你應該這樣做

    equ_len = strlen(equation); 
    j = 0; 
    for (i = 0; i < equ_len; i++) { 
         if (j <= 2 && isdigit(equation[i])) { 
           data[j] = equation[i]; 
           j++; 
         } 
         if (j > 2) break; 
    } 
    
  4. printf("%d\n", data[k]);應該printf("%c\n", data[k]);

    %d會給data[k]的ASCII代碼,例如,如果該值data[k]是字符'1',%d將打印50(ASCII碼爲'1')而不是1.


這裏是基於OP碼我最後的代碼,:

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

int main(void) 
{ 
    int i,j,k; 
    char equation[100]; 
    int data[3]; 
    int equ_len; 


    printf("Enter an equation: "); 
    fgets(equation, 100, stdin); 

    equ_len = strlen(equation); 
    j = 0; 
    for (i = 0; i < equ_len; i++) { 
     if (j <= 2 && isdigit(equation[i])) { 
      data[j] = equation[i]; 
      j++; 
     } 
     if (j > 2) break; 
    } 

    for (k = 0; k <= 2; k++) { 
     printf("%c\n", data[k]); 
    } 

    return 0; 
} 

與測試:

$ ./a.out 
Enter an equation: 1 + 2 + 3 
1 
2 
3 
+0

感謝您的回覆。我修復了我的代碼,但仍然出現錯誤,這次重複了3次,例如「50 50 50」,無論輸入如何。 – ZumbaLover69

+0

@ ZumbaLover69我已經更新了我的答案,試試看。 –

+0

這是一個乾淨而簡單的解決方案。你是救世主,謝謝。 – ZumbaLover69