I would like to know about the getchar() logic in the following codes...
printf("Type up to 25 characters and then press Enter. . . \n") ;
for (i = 0; i < 25; i++)
{
msg[ i] = getchar() ;
if (msg[ i] == ' \n' )
{
i--;
break;
}
}
putchar(' \n' ) ;
for (; i >= 0; i--)
{
putchar(msg[ i] ) ;
}
In the above code if i input a name,say "STACKEXCHANGE" and then hit enter it will display the word properly..but the below code works differently..
printf("What are your two initials?\n") ;
firstInit = getchar() ;
lastInit = getchar() ;
In this example, if i type "ST" and then hit enter, 'S' will be stored in firstinit, while "\n" will be stored in lastInit instead of 'T'.
How does this happen? Isn't 'T' the second character input into the buffer. Infact \n is the third character in the buffer. so why does \n get stored. correct me if iam wrong, but the buffer is released when \n is pressed or entered, then why is it again being stored in the next getchar() function.
Why is the first code executed differently then? I mean if i input "stackexchange" and hit enter "t" is stored as the second character as is wanted, but it in the second example if the same "st" is typed and "enter' is input, the "t" is not stored as the second input, but instead "enter' is taken as the second input.
I am sorry if my typing is confusing... basically i want to know the logical flow in both codes, how it happens behind the scene..