0
#include <stdio.h>
#include <string.h>

struct acho {
    char ahn[50], add[200];
    long int a, bal;
};

int main() {
    struct acho s;
    printf("enter name: \n");
    gets(s.ahn);
    printf("enter number: \n");
    scanf("%ld", &s.a);
    printf("enter address: \n");
    gets(s.add);
    printf("enter balance: \n");
    scanf("%ld", &s.bal);
    printf("Name: %s \n", s.ahn);
    printf("Account number: %ld \n", s.a);
    printf("Address: %s \n", s.add);
    printf("Balance: %ld \n", s.bal);
    return 0;
}

Why isn't this code an taking input for address? Can anyone find the bug please? I have tried both input methods like gets and fgets but it is not taking input for address in any case.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • Post exact input used, output seen, output expected. – chux - Reinstate Monica Nov 17 '21 at 14:48
  • 3
    Note: `scanf("%ld", &s.a);` does _not_ read an entire _line_, only up to the text that represents the number. The following `gets()` will read the remainder even if it is only `"\n"`. Tip: use `fgets()` for all user input and not use `scanf()`. – chux - Reinstate Monica Nov 17 '21 at 14:49
  • 3
    Don't mix `gets` and `scanf`. BTW `gets` has been deprecated 20 years ago. Use `fgets` and read this: https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input – Jabberwocky Nov 17 '21 at 14:52

1 Answers1

0
#include <stdio.h>
#include <string.h>

struct acho {
    char ahn[50], add[200];
    long int a, bal;
};

int main() {
    struct acho s;
    printf("enter name: \n");
    fgets(s.ahn,50,stdin);
       printf("enter number: \n");
    scanf("%ld", &s.a);
    getchar();
    printf("enter address: \n");
    fgets(s.add,200,stdin);
    printf("enter balance: \n");
    scanf("%ld", &s.bal);
    printf("Name: %s \n", s.ahn);
    printf("Account number: %ld \n", s.a);
    printf("Address: %s \n", s.add);
    printf("Balance: %ld \n", s.bal);
    return 0;
}
  1. use fgets() instead of gets(). gets() is inherently unsafe, because it copies all input from STDIN to the buffer without checking size. This allows the user to provide a string that is larger than the buffer size, resulting in an overflow condition.
  2. your address statement is reading a newline character add a getchar() before printf("enter address: \n"); to read a newline character.
vegan_meat
  • 878
  • 4
  • 10