C: problem skipping user input

Ð88

Fully Optimized
Messages
4,775
I'm using C in my program (a big part of my issue already) and a part of it requires a user to enter a name to be read from a text file. I started by using fgets but that created issues in itself. I reverted to using scanf which saw an improvement but here's what happens:

There is a loop that asks the user if she wishes to read, write or delete. If I select read, it then asks how many names I want to read. Then it goes through a loop of asking for a name, calling a procedure and returning a result and will loop for the number of names I chose to read.
Now that exits, and it asks the user if she wants to continue, if yes, it loops back and asks for an option ("no" exits obviously). Now this time if I select read, it prompts for the number of names to read, i enter a number but then it skips asking for any names and goes straight to where it asks if I want to continue.

Now here's a portion of the code:
Code:
  if (strcmp(selection, "read") == 0) {
   	   printf("Enter number of names: ");
   	   scanf("%d", &numNames);
   	    		if (numNames > 5) {
   	    			fprintf(stderr, "Number of names must be 5 or less\n");
   	    			exit(0);
   	    		}
   	    			while(j < numNames){
   	 					printf("Enter name: ");
   	 					scanf("%s", name);
.
.
.

and at the end where it asks if you wish to continue:

Code:
.
.
.
   	printf("Do you wish to continue? [Y/N]: ");
   	scanf("%s", answer);
   }
	while (strcmp(answer, "Y") == 0 || strcmp(answer, "y") == 0);

any ideas how to fix it?
 
I know very little about c but did you check your variables. you may have the set incorrectly. also check your if statements. I would try setting &numNames to 0 prior to entering the loop. By doing that will remove any trash in that memory location. Also double check your syntax, the smallest syntax error can through the whole program off.
 
There is a small problem though: fgets also reads the <return> the user typed to ... The basic method of skipping input is to use the '*' to indicate ...
 
Back
Top Bottom