help with input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nickyeng
    Contributor
    • Nov 2006
    • 252

    help with input

    what is wrong with this code:
    Code:
    char Invalid() {
    	char ignore[1];
    
    	printf("\t\tInvalid choice! Please press any key to try again.\n");
    	gets(ignore);
    
    	return atoi(ignore);
    }
    actually i wanted it to be wait until user press any key before return anything.

    but it seems that it didn't stop after printf() is output for user to press any key, and it just return.

    how it happens?
    i want it to stop and wait for user to press any key, then return.
    I have to write it in C language(no C++).

    please help
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    the newline character which you entered on the end of your last input is probably left in the input stream (so gets() returns immediatly)- you need to remove it. try
    Code:
    char Invalid() {
    	char ignore[1];
           cin.ignore(1000,'\n');        // extract characters up to and including \n
    	printf("\t\tInvalid choice! Please press any key to try again.\n");
    	gets(ignore);
    
    	return atoi(ignore);
    }

    Comment

    • nickyeng
      Contributor
      • Nov 2006
      • 252

      #3
      Originally posted by horace1
      the newline character which you entered on the end of your last input is probably left in the input stream (so gets() returns immediatly)- you need to remove it. try
      Code:
      char Invalid() {
      	char ignore[1];
             cin.ignore(1000,'\n');        // extract characters up to and including \n
      	printf("\t\tInvalid choice! Please press any key to try again.\n");
      	gets(ignore);
      
      	return atoi(ignore);
      }
      cin is c++ syntaz rite?

      i dont want cin for input stream...
      can you change that line to C language based ?

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        Originally posted by nickyeng
        cin is c++ syntaz rite?

        i dont want cin for input stream...
        can you change that line to C language based ?
        sorry - tend to think in C++ all the time!
        try calling gets() twice, once to remove previous input and again to wait for the newline key to be hit
        Code:
        char Invalid() {
        	char ignore[10];
               gets(ignore);       // extract characters up to and including \n
        	printf("\t\tInvalid choice! Please press any key to try again.\n");
        	gets(ignore);
        	return atoi(ignore);
        }
        make your ignore[] array larger than 1 in case there are a number of characters in the input stream

        Comment

        • nickyeng
          Contributor
          • Nov 2006
          • 252

          #5
          thanks alot horace1.
          :)

          nick

          Comment

          Working...