|
From: Adam J. <aj...@i-...> - 2007-07-16 16:18:06
|
>>Hello,
>>I have got a problem I don't understand very much.
>>I have in my code:
>>#include<stdio.h>
>>int main()
>>{
>>char str[10];
>>getchar ();
>>gets (str);
>>printf ("%s\n", str);
>>return 0;
>>}
It would be helpful to all of us if you could explain why you feel it
necessary to use getchar() the gets() the way you do. What are you trying to
accomplish by doing it this way.
getchar() waits for any keypress to continue, and gets will wait until it
encounters the newline or end of file before continuing.
You also have a potential to corrupt memory here. What happens if the person
enters a string longer than 10 Char. You also assume which is not very good
that the system will allocate a char str[10] without checking to see if it
can do it with a malloc first. On memory allocations you need to check
first, and if it fails exit your program gracefully.
>>In this case it seems the program is ignoring the "gets ()" command. After
I press some key and >CR>It stops and doesn't wait for line input. If I do
not have there the "getchar () I >>can input a line.
If you hit any key and the CR then the single key press goes to getchar()
the <CR> goes to the gets() which terminates that call. You should just hit
any key, then type in your string and then hit CR when you are done. The
getchar() does not require you to hit CR in order for it to accept the key
press. This should work.
-Adam Jones
|