An Nguyen
An Nguyen

Reputation: 3

Can't enter name gets

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

struct student {
    char name[30];
};
typedef struct student sv;
int main() {
    int i;
    sv basedata[50] ;
    int totalstudent;
    do
    {
        printf("How many people are there: ");
        scanf_s("%i", &totalstudent);
    } while (totalstudent<0);
    fflush(stdin);
    for ( i = 0; i < totalstudent; i++)
    {
        printf("Person %i name: ", i + 1);
        gets(basedata[i].name);
    }
}

output: How many people are there: 1 Person 1 name:
D:\hello\chuong7\x64\Debug\chuong6.exe (process 26572) exited with code 0. Press any key to close this window . .

Why I can't enter name for Person 1 name when run my program, my program pass to end and I can't gets(basedata[i].name). Sorry I'm just study English picture here

Upvotes: 0

Views: 72

Answers (1)

zwol
zwol

Reputation: 140826

This program has many bugs, but the one that is specifically tripping you up is that you are calling scanf, which doesn't read input in lines, and then gets, which does. After the scanf, the carriage return that the user typed after the number is still waiting to be read. gets reads that carriage return instead of the additional input that you are trying to prompt for. Your call to fflush(stdin) does not change this; what fflush(stdin) does, varies from system to system, but it never does what people seem to expect it to do.

In addition, gets is dangerous and should never be used, scanf is broken-as-specified and should never be used, and all of the _s functions that Microsoft's compilers like to push on you are unportable and don't fix the problems Microsoft was trying to solve, and (wait for it) should never be used.

Here's what you should do instead:

  1. Put #define _CRT_SECURE_NO_WARNINGS 1 at the top of your file (before all the #includes) to make MSVC stop giving you bad advice.
  2. Use fgets, nothing else, to read all lines of input from the user.
  3. Use strtol to convert the decimal number input to a machine integer.
  4. Since you are using a statically allocated array of records, check whether the number input is bigger than the size of the array, before entering the loop.

Best of luck.

Upvotes: 2

Related Questions