2011-04-03 61 views
0

欲輸入:C字符串數組問題

ABC DEF GHI JKL

和輸出應爲:

abc 
def 
ghi 
jkl 

欲每個字符串存儲在數組中然後使用for循環打印每個位置。

我有這樣的代碼:

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

int main() 
{ 
    char vector[100]; 
    int i = 0; 
    int aux = 0; 
    while (i < 5) 
    { 
     scanf("%s", &vector[i]); 
     i++; 
     aux+= 1; 
    } 

    for (i=0;i<aux;i++) 
    { 
     printf("%s\n", &vector[i]); 
    } 

    return 0; 
} 

我在做什麼錯?

第二個問題:

如何更改代碼停止閱讀我的投入,當我按CTRL d並打印輸出?

回答

2

你正在做一個字符的地址,在您的「載體」,在填寫了弦數代替。這些修改:

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

int main() 
{ 
    char vector[5][100]; /* five times 100 characters, not just 100 characters */ 
    int i = 0; 
    int aux = 0; 
    while (i < 5) 
    { 
     scanf("%s", vector[i]); /* notice the & is gone */ 
     i++; 
     aux+= 1; 
    } 

    for (i=0;i<aux;i++) 
    { 
     printf("%s\n", vector[i]); /* notice the & is gone */ 
    } 

    return 0; 
} 

對於CTRL-d位,你可以把它停在輸入的最後一讀,但你必須管理獲得大量輸入的(所以你可能必須動態分配你「解析」你的字符串的緩衝區scanf

+0

謝謝。完成你所說的,它的工作。改變while循環while(我<5 && scanf(「%s」,vector [i])!= EOF)'現在它停止了我按ctrl d,但如果我輸入'abc'並按下ctrl d it在「c」輸入後打印'a',在新行上打印'b'和'c'。我該如何改變它? – Favolas 2011-04-03 17:09:13

+0

@Favolas你可以發佈你的新代碼?用它回答你(顯然是新的)問題會更容易。 – rlc 2011-04-03 21:01:20

+0

感謝您的幫助。這是http://stackoverflow.com/questions/5535916/c-while-loop-stopping-at-e-但--printing-result-in-a-new-line – Favolas 2011-04-04 08:01:30

0

您正在使用一個字符數組來存儲多個字符串。你可以使用一個二維數組是這樣的:

char vector[STRING_NUM][STRING_MAX_LENGTH] 
+0

謝謝。現在我明白了 – Favolas 2011-04-03 17:04:27

0

你有一個字符數組(即一個字符串)。

如果你想要一個字符串數組,這是字符數組的數組:

char vector[NUM_STRINGS][NUM_CHARS]; 
+0

謝謝。現在我明白了 – Favolas 2011-04-03 17:04:04