"Why for loop never ends?"
First things first, I do not think that the loop is infinite. For me it seems that you are just confusing %s
with %c
and interpret the waiting for more input as loop that "never ends".
You didn´t provided sufficient ressources to rebuild your issue, though.
But let´s get started:
The %s
conversion specifier of scanf()
is for reading a string, not a single character. If you want to read a single character per iteration, use scanf("%c", &name[i]);
or name[i] = getchar();
instead of scanf("%s", &name[i]);
in the for
loop.
Your loop condition i <= ln
is faulty, as you attempt to write one character more than expected with it, because index counting starts at 0
, not 1
. Use i < ln
instead.
A string needs to have a terminating null character at the end. name
needs to have one element more than to just hold the letters of the input name. Also place name[ln] = '\0';
after the loop to insert a null character in the last element of VLA name
.
Note:
If you want to read a variable amount of characters from stdin
which is determined at run-time, you don´t need to read each character separate and stop until the counter reaches ln - 1
.
Reading a string with a variable amount of characters is one point, where fgets()
is more appropriate than scanf()
.
Use fgets (name, sizeof(name), stdin);
which ensures that the read string plus the string-terminating null character will fit exactly into name
and catch the name once.
int ln;
printf("How many letters are in your name?\n");
scanf("%d", &ln);
getchar(); // catching left newline from scanf.
char name[ln + 1]; // +1 for null character.
printf("Ok...enter your name: \n");
fgets(name, sizeof(name), stdin); // Will read the name and append the null character.
getchar(); // catching left newline from fgets.