Hi guys,

I'm having trouble with this particular code

#include <stdio.h>
 
int main()
{
    char aChar;
    printf("Please enter a character: ");
    scanf("%c",&aChar);
 
    while (aChar!='x')
    {
        printf("The Letter is %c\n", aChar);
 
        printf("Please Enter another character: ");
        scanf("%c", &aChar);
    }
    return 0;
 
}

The output is:
Please enter a character: q
The letter is q
Please enter another character: The Letter is

i've got a feeling that when i enter a character, '\n' gets included, is there a way to remove it?

Try running this code

#include <stdio.h>
 
int main()
{
    char aChar;
    printf("Please enter a character: ");
    scanf("%c",&aChar);
 
    while (aChar!='x')
    {
        printf("The Letter is %c or the integer is->%d\n", aChar, aChar);
 
        printf("Please Enter another character: ");
        scanf("%c", &aChar);
    }
    return 0;
 
}

Can you figure out what's going on? Hint 10 is new line.

aahhh, i see '\n' has an ascii value of 10.
so when an input is given say 'e', '\n' tags along.
now to find a way to either remove it or to consume it with the user input??

aahhh, i see '\n' has an ascii value of 10.
so when an input is given say 'e', '\n' tags along.
now to find a way to either remove it or to consume it with the user input??

Well almost. '\n' doesn't tag along, its entered by the user to indicate he's done inputing values..

Your example - When a user enters a value 'e' he/she really enters/types 'e' and then hits/types the enter key which is the '\n'.

ahhh, i understand now.
I've being searching around, just i cant figure out a way of removing it, or including it.
I've also seen some forums, where they suggest not to use scanf as it leaves a newline in the input stream.
but we have to use scanf.
is there another possible solution?

A simple method would be

char aChar;
char nline;
printf("Please enter a character: ");
scanf("%c%c",&aChar, &nline);

Thanks a lot gerard4143

You can also use this

scanf("%c",&aChar);
fflush(stdin);        /*It clears the input*/

You can also use this

scanf("%c",&aChar);
fflush(stdin);        /*It clears the input*/

No, it's wrong because fflush() is only defined for output streams. Just because it happens to work for you doesn't mean it's correct.

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.