[Help] For loop Question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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]);
Technically, you're entering 3 names, but it's not obvious to you, let me rewrite your program and show you exactly what I mean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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.
Last edited on
Topic archived. No new replies allowed.