moon shines
moon shines

Reputation: 88

input of character in c

i am trying to read input character until it is 'a'.however i need all the characters typed until a.the problem is it is also taking new line as a character.that is when i press a character(say f) an enter it is taking f as well as new line char in the next loop.

#include<stdio.h>
int main()
{
    char val;
    while(1)
    {
        printf("\nenter val: (a to stop)");
        scanf("%c",&val);
        printf("val is %d\n",(int)val);
        if(val=='a')
            break;
        else
            continue;
    }
    return 0;
}

output:

enter val: (a to stop)f
val is 102

enter val: (a to stop)val is 10

enter val: (a to stop)

Upvotes: 0

Views: 179

Answers (3)

Ayush Agarwal
Ayush Agarwal

Reputation: 46

You can also use gets() if you want to skip newline character as shown below

#include<stdio.h>
int main()
{
    char val;
    while(1)
    {
        printf("\nenter val: (a to stop)");
        gets(&val);
        printf("val is %d\n",(int)val);
        if(val=='a')
            break;
        else
            continue;
    }
    return 0;
}

Upvotes: 1

Vishnu CS
Vishnu CS

Reputation: 851

This is another way of implementing the same logic you want.You could add a space before the format specifier when you use scanf()

scanf(" %c",&val); 

The leading space tells scanf() to skip any whitespace characters (including newline) before reading the next character.

As many of them suggested you can use fgets or fgetc.

Upvotes: 1

user13387119
user13387119

Reputation:

Newline is a character, and the value of it is 10. If you don't want it, check if it is newline before printing.

include<stdio.h>
int main()
{
    char val;
    while(1)
    {
        printf("\nenter val: (a to stop)");
        scanf("%c%*c",&val);
        printf("val is %d\n",(int)val);
        if(val=='a')
            break;
        else
            continue;
    }
    return 0;
}

Upvotes: 1

Related Questions