Reputation: 3
#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
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:
#define _CRT_SECURE_NO_WARNINGS 1
at the top of your file (before all the #include
s) to make MSVC stop giving you bad advice.fgets
, nothing else, to read all lines of input from the user.strtol
to convert the decimal number input to a machine integer.Best of luck.
Upvotes: 2