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


int main()
{
    struct student 
    {
        int roll;
        char grade;
    };
    struct student s1,*p;
    p=&s1;
    printf("Enter the roll no.: ");
    scanf("%d", &s1.roll);
    printf("Enter the grade: ");
    scanf("%c", &s1.grade);
    printf("Roll no. %d\nGrade %c", (*p).roll,p->grade); 
    return 0;
}

apparently I can solve this by adding a space in the second scanf() but if I make another program that just takes two characters(or valies in strings) one after another and then print them, it works fine even without accounting for the buffer input. Why is that?

ryuuga
  • 1
  • 1
  • Reading another character consumes the newline left in the input stream when the first field was read. If you run your program in a *debugger* and look at the actual values of the fields being processed you'll see this. Regardless, if you have a comparison question (this code does this; that code does that) *both* need to be included in your question. – WhozCraig Jan 08 '22 at 08:34
  • `scanf("%d%c", ...)` (or in two statements) means: read characters (optionally preceded by discarded whitespace) for an integer and 1 more character (may be whitespace) into variables. You will be better off if you do not use `scanf()` for user input and stick with `fgets()` (and/or `getchar()`). Anyway... if you must keep on using `scanf()` try `scanf("%d %c", ...)` to read an integer (optionally preceded by ignored whitespace) skip whitespace and read 1 more character. **The `"%c"` conversion specifier does not do the "ignoring optional leading whitespace".** – pmg Jan 08 '22 at 08:38
  • Unrelated to your problem, there's a couple of things about the code that I wonder about: What is the use of the pointer `p`? Why use both the syntax `(*p).roll` and `p->grade`, and not use only one of the syntaxes (preferably the "arrow" one)? – Some programmer dude Jan 08 '22 at 08:43
  • @Someprogrammerdude I was trying pointers out. – ryuuga Jan 09 '22 at 10:08

0 Answers0