Home > Blockchain >  Why is my code not taking the input for address?
Why is my code not taking the input for address?

Time:11-18

#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.

CodePudding user response:

#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.
  •  Tags:  
  • c
  • Related