-9
#include <stdio.h> 

struct Bank {
    char name[500];
    int mobile;
    float balance;
};

int main() {
    int i;
    struct Bank a[100];

    for (i = 0; i < 3; i++) {
        printf("Enter the name of person %d: ", i + 1);
        gets(a[i].name);
        printf("Enter the mobile of person %d: ", i + 1);
        scanf("%d", &a[i].mobile);
        printf("Enter the mobile of person %d: ", i + 1);
        scanf("%f", &a[i].balance);
    }

    for (i = 0; i < 3; i++) {
        puts(a[i].name);
        printf("His Balance is: %f", a[i].balance);
        printf("His Mobile number is : %d \n\n", a[i].mobile);
    }

    return 0;
}

Try running this the user input requests don't come like I want them to, just run it and one would understand. What am I doing wrong?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
iDream
  • 1
  • Welcome to Stack Overflow! It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Paul R Sep 04 '16 at 21:11
  • what do you want?? – Jean-François Fabre Sep 04 '16 at 21:11
  • 1
    `stdout` is linebuffered, you should add a `\n` at the end of your `printf`s or flush the buffer. – mch Sep 04 '16 at 21:11
  • doesn't work, tried. I use visual studio. – iDream Sep 04 '16 at 21:31
  • 1
    One problem is that you're using `gets()` — don't! See [Why the `gets()` function is too dangerous to be used, ever](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used). – Jonathan Leffler Sep 04 '16 at 21:45
  • 1
    Asking for the mobile twice is a copy'n'paste error. – Jonathan Leffler Sep 04 '16 at 21:46
  • Check I reposted the code below – iDream Sep 04 '16 at 21:50

1 Answers1

2

The reason it's not working as expected is because there is a newline character left on the input buffer on the second and third iteration to gets(), presumably from the previous "enter" hit.

It works as expected (kind of, see below) if you change the gets() call to scanf("%s", a[i].name).

Please note that:

  • this code is badly vulnerable to buffer overflow on multiple lines (all scanf() and the gets() call) - see here, or here, or here, etc., bottom line: you should not use gets() at all, nor scanf() without a boundary

  • you have a typo in the third printf and it again asks for the mobile number

Community
  • 1
  • 1
Gabor Lengyel
  • 14,129
  • 4
  • 32
  • 59