I am wondering what is wrong with my code. I normally use scanf but am trying get the hang of fgets. But when I try to print a char array where each element of the array is on a separate line, but even though I defined the limit of the array as an arbitrarily high number, it only has a limit of eleven lines. I am a beginner programmer so try to be as simple as you can.
#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;
}
I am wanting to get a result like this.
Enter string: Hello
H
e
l
l
o
But it turns out quite differently
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
You need to check that str[i]
is NOT EQUAL to '\n'
instead of checking i!='\n'
.
As @BLUEPIXY pointed out it means i != 10, being '\n' equal to 10 in the ASCII code.
So change the condition to:
for (int i=0;i <max_line && str[i]!='\n'; i++) {