0

CODE:

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

int main(){
    struct mobile{
        char N[10];
        int ram, pixel, price;
    }B[5];
    int min;
    char trash;

    for(int i = 0; i < 5; i++){
        printf("Enter Mobile Name: ");
        fgets(B[i].N, sizeof(B[i].N), stdin);
        printf("Enter features (ram/camera pixels/price): ");
        scanf("%d%d%d", &B[i].ram, &B[i].pixel, &B[i].price);
        printf("\n");
    }
}

The program is not accepting value for name of mobile second time. It prints Enter mobile name but don't take value then print Enter features and ask for value. I tried adding a second scanf above printf("\n"); but didn't work. Help please. Thanks.

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33
  • 1
    If you're using C then remove the C++ tag. If you're using C++, then remove the C tag and probably don't use `printf` and `scanf` and such. – ChrisMM Mar 26 '21 at 16:31

1 Answers1

0

Remove \n from buffer

scanf leaves a newline in the buffer, which is then read by fgets. The other problem is, that you aren't dividing the user input using a delimiter so I would put a space or a slash between the type specifiers %d:

scanf("%d/%d/%d\n", &B[i].ram, &B[i].pixel, &B[i].price);

The input should then be something like this:

Enter specs (ram/pixels/price): 8/12/500

The trailing character \n is now being read, but it isn't stored in any variable.

Remove \n from fgets() input

This doesn't cause your problem, but I would also remove the trailing \n from the fgets() input, because it's probably not supposed to be part of the phone's name.

#include <string.h>

fgets(B[i].N, sizeof(B[i].N), stdin);
B[i].N[strcspn(B[i].N, "\n")] = '\0';
Andy Sukowski-Bang
  • 1,402
  • 7
  • 20
  • Does B[i].N[strcspn(B[i].N, "\n")] = '\0'; remove all the '/n' from whole sentence or the last one? Thanks, it worked. – Pankaj-Talesara Mar 27 '21 at 03:39
  • `B[i].N[strcspn(B[i].N, "\n")] = '\0';` will terminate the string at the first occurrence of `\n` by overwriting it with `\0`. In your case there is only going to be one `\n` in the end of the string, because `fgets` stops reading user input when enter is pressed. – Andy Sukowski-Bang Mar 27 '21 at 06:42
  • So if I pass *A* and type *abcdAefgh* will function terminate whole *efgh* at last and only *abcd* will be stored? – Pankaj-Talesara Mar 27 '21 at 14:09
  • @Pankaj-Talesara Yes, if you did this `B[i].N[strcspn(B[i].N, "A")] = '\0';` and typed `abcdAefgh`, the `A` would be overwritten with `\0`, so the string `B[i].N` would be `abcd`. – Andy Sukowski-Bang Mar 28 '21 at 14:40