I have the following program
#include <stdio.h>
main()
{
char ch[10];
gets(ch);
printf("\nTyped: %s\n\n", ch);
int i = 0;
while ( ch[i] != '\0' )
{
printf("Letter: %c\n", ch[i]);
i++;
}
printf("\nTyped: %s\n\n", ch);
}
and here is the output when i typed “Hello world is good”
hello world is good
Typed: hello world is good
Letter: h
Letter: e
Letter: l
Letter: l
Letter: o
Letter:
Letter: w
Letter: o
Letter: r
Letter: l
Letter:
Typed: hello worl♂
Why i am getting two different output for same command after while loop? does while loop has anything to do with it.. please help..
Your character array
chonly has space for 10 chars. You typed something longer than 10 chars and tried to store it in that array, effectively writing beyond the end of the array into space that’s not reserved for anything (or at least isn’t reserved for your characters). You got lucky in this case and didn’t write over anything important (your program didn’t crash), but subsequent code comes along (theprintf(), yourint i, etc.) and changes that memory (it’s the stack, after all, so it gets used in FIFO order).Change your
char ch[10]tochar ch[2048]to give yourself a larger buffer to type into. You might also usefgets()instead ofgets()so that you can limit the size of the input to your buffer size. If you usegets(), heed the warning on the man page: