1

My logic in this code is to prompt the user for some inputs(int,float and a char) and print them back out saying "this is what you typed".Everything works fine and it compiles ok without errors or warnings but the "char" taken from the user is not being printed.What do I do to solve the issue? Also,the scanf() containing the %c for char ignores the "\n" that I put at the end of it.How to solve this one too? Heres my code :

#include <stdio.h>
#include <conio.h>

int main()
{
    int a;
    float b;
    char c;
    
    printf("Your Integer : ");
    scanf("%i",&a);
    
    printf("Your Float : ");
    scanf("%f",&b);
    
    printf("Your Char : ");
    scanf("%c/0\n",&c);
    
    printf("              ****You Inputted the Following Values : ****\n\n");
    printf("The INTEGER Value Is : %i\n\nThe FLOAT Value Is : %f\n\nThe Character Value Is : %c " , a , b , c);
    
}

But I get a blank space for the char value!Help please! And I am using DEV C++ for this.That's the requirement of our University.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Uzair_07
  • 141
  • 1
  • 9

1 Answers1

1

Probably the newline character you entered after the floating-point variable is scanned into c.

You can add a space before %c like " %c/0\n" to have scanf() ignore whitespace characters including newline character.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 3
    Please refrain from answering what is a clear as day duplicate... – Marco Bonelli Nov 05 '20 at 16:13
  • Marco Bonelli I am a student in my first year and lets face it my first day in CS class,that's bound to happen – Uzair_07 Nov 05 '20 at 16:19
  • 1
    @Uzair_07 your question was presented quite well. – Weather Vane Nov 05 '20 at 16:21
  • Weather Vane Thankyou! Just one more question,I need a little more explanation about this why it happened and an extra space solved it? – Uzair_07 Nov 05 '20 at 16:22
  • The format specifiers `%d` and `%s` and `%f` automatically filter leading whitespace, but `%c` and `%[...]` and `%n` do not. You can instruct `scanf` to do so by adding a space just before the `%`. The `scanf` conversion stops at the first character it cannot convert, which is typically (but not necessarily) a space or a newline, and that character remains in the input buffer. – Weather Vane Nov 05 '20 at 16:24
  • @Weather Vane Thank you so much! – Uzair_07 Nov 06 '20 at 04:38