Click here to Skip to main content
15,889,505 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
why doesnt get char() always take input when we call it multiple times.....the following code below only ask user input for first time....

What I have tried:

int main(){
int c;
printf("Enter character");
c = getchar();
c=getchar();
c=getchar();

putchar(c);

}
Posted
Updated 31-Mar-17 9:12am

getchar - C++ Reference[^] waits for a key to be pressed and returns the code when that happens or there is already a key in the input queue.

You are calling it three times and assign the return value to the variable c. So the first two characters are ignored and only the third one is echoed on the screen.

If you want to process multiple characters you have to use a loop like
C++
do
{
    c = getchar();
    putchar(c);
}
while (c != 0x0d)
 
Share this answer
 
Quote:
the following code below only ask user input for first time....

Asking for user input is
C++
printf("Enter character");

How many times do you expect this sentence to be printed ?
With the debugger, put a breakpoint and follow step by step execution and pay attention to the variablr c.

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900