2011-04-03 68 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