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;
}

I couldn't find the problem so I added in a bunch of header files just in case that was causing it. I have been getting similar problems in a lot of other codes that have something do with structs, strings, gets(), fgets().

ryuuga
  • 1
  • 1
  • 2
    The `%c` reads the next character, including whitespace — meaning that it reads the newline (Enter key) left over from entering the roll number. Place a space before the percent sign to skip whitespace and read a non-whitespace character. – Dúthomhas Jan 03 '22 at 06:49
  • You can simply add fflush(stdin); just below the line where you are reading roll no. This clears any input buffer and moves to the next line without skipping it. – csgeek Jan 03 '22 at 06:57
  • @csgeek No. https://stackoverflow.com/q/2979209/6699433 – klutt Jan 03 '22 at 07:25
  • @Dúthomhas It works when I do that but if that was causing the problem, then when we make a program that just takes two characters one by one then prints them, it works fine(without needing to address the buffer input)? Also when I run the roughly the same program in a loop but use either gets() or fgets() to take the value in the string, I encounter the same problem. Any solution for that? – ryuuga Jan 04 '22 at 13:47

0 Answers0