#include <stdio.h>
void main()
{
char name[10][15];
int num,k;
printf("Enter the number(s) of names you wish to input:");
scanf("%d",&num);
printf("Enter the %d name:\n",num);
for (k=0;k<=num;k++)
{
gets(name[k]);
}
printf("\nThe names are:");
for (k=num;k>=0;k--)
{
printf("\n%s",name[k]);
}
printf("\n");
}
If the I input num=2, then k=0;k<=2 and it should loop 3 times right (k=0,k=1,k=2)? But when I execute this program, it only loops 2 times for the gets(name[k]);
#include <cstdio>
int main()
{
char name[10][15];
int num,k;
printf("Enter the number(s) of names you wish to input:");
scanf("%d",&num);
for (k=0;k<=num;k++)
{
printf("\nEnter name %d: ",k);
gets(name[k]);
}
printf("\nThe names are:");
for (k=num;k>=0;k--)
{
printf("\n%s",name[k]);
}
printf("Have a good day.");
printf("\n");
return 0;
}
There is an empty line in the buffer, and is read for name[0]. I know how to fix this using C++, but not C. I was unable to find anything in the reference section that'd allow you to ignore buffer characters.
Edit: I finally stumbled across the solution. You simply add fflush(stdin); after your scanf for num.