2017-05-01 132 views
0

我想知道我的代码有什么问题。我通常使用scanf,但我试图得到fgets的窍门。但是,当我尝试打印一个char数组,其中数组的每个元素都在一个单独的行上,但即使我将该数组的限制定义为任意高数字,它也只有十一行的限制。我是一名初学者程序员,所以尽量尽可能简单。打印字符数组

#include <stdio.h> 
#define max_line 4096 
int main(void) { 
    char str[max_line]; 
    printf("Enter string: "); 
    fgets(str, max_line, stdin); 
    for (int i=0;i <max_line && i!='\n'; i++) { 
     printf("%c\n", str[i]); 
    } 
    return 0; 
} 

我想得到这样的结果。

Enter string: Hello 
H 
e 
l 
l 
o 

但事实证明,完全不同

Enter string: Hello 
H 
e 
l 
l 
o 
/n //Sorry, I don't know how to add new lines in stackoverflow, but I think you get the idea. 
/n 
/n 
/n 
/n 
+3

'我= '\ n'' - >'STR [1]!=' \ n'' – BLUEPIXY

+0

所以在我的病情,我只是改变它对? – danielwestfall

+0

为什么'我!='\ n''? Comeon,三思! ;-)你想要测试什么*不是新行? – alk

回答

2

您需要检查str[i]是否为不等于'\n'而不是检查i!='\n'。 正如@BLUEPIXY指出的那样,它意味着i!= 10,在ASCII代码中'\ n'等于10。

所以更改条件:

for (int i=0;i <max_line && str[i]!='\n'; i++) { 
-2

试试这个代码

int main(void) { 
    int i; 
    char str[max_line]; 
    memset(str, 0x0, max_line); 
    printf("Enter string: "); 
    fgets(str, max_line, stdin); 
    for (i=0;i < strlen(str) ; i++) { 
     printf("\n%c", str[i]); 
    } 
    return 0; 
} 

末(你好)之后,空字符不存在,因此垃圾输出。

+0

请参阅OP的评论。 – alk

+0

对不起,修改后的代码。 – Kamal