I coded a simple program that pretends two users input random characters and the program tells you which user wrote what

#include <stdio.h>

int main(void)
{
    int x;
    char user;
    char ch; 
    puts("type a character");
    for(x = 0;x < 9; x++)
    {
        if(x%2 == 1)
        {
            user = 'x'; 
        }
        if(x%2 != 1)
        {
            user = 'y'; 
        }
        ch = getchar();
        printf("user %c inputs %c\n",user,ch);
    }
}

The output should look something like this:

type a character:
a

user y inputs a

type a character:
b

user x inputs b

type a character:
e

user y inputs b

but instead it looks like this:

type a character
a
user y inputs a
user x inputs 

b
user y inputs b
user x inputs 

c
user y inputs c
user x inputs 

d
user y inputs d
user x inputs 

e
user y inputs e

which means user x never gets to type a character

Double your getchar()'s, and all will be well.

When you enter a char, you hit the the enter key, putting a newline ('\n') char into the keyboard stream (stdin). The first getchar() pulls off only the char you pressed BEFORE you hit enter, leaving the newline behind - and lets it get picked up by the next getchar().

You enter: 'A', but stdin has: 'A''\n', and that's your problem.

ch=getchar();
getchar();  //add this line

solves the problem.

Wow thanks!
is there a function like perl's chomp in C?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.