Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5428
Number of posts: 16943

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Input validation Posted by Minis on 5 Oct 2009 at 11:18 AM
Hi!
I'm trying to validate the input as 'A' or 'P' with the following function:
char Get_l(void)
{
//declare local variables
char v_let, clearkbd;

printf("Enter A(for AM) or P(for PM):");
v_let = getchar();
while((clearkbd = getc(stdin))!= EOF && clearkbd != '\n');

//Loop until the user enters either A or P
while(v_let != 'A' && v_let != 'P')
{
printf("The letter you entered is not valid. Please enter \
A(for AM) or P(for PM):");
v_let = getchar();
while((clearkbd = getc(stdin))!= EOF && clearkbd != '\n');

}//end of while

return v_let;

}//End of Get_l

If I test it without any previous data entered, it works great. If there was data entered before, and I type A, I get "invalid" message. Can you help me find the problem?
Report
Re: Input validation Posted by pseudocoder on 13 Oct 2009 at 2:50 AM
The best I can recall, all of C's standard input functions are buffered, so they may return junk until the buffer is cleared. I'm also not sure if a char can be used for EOF... I *think* it has be of type int, but I'm still quite rusty with C / C++.

When I played around with C a few years ago, I used something like below to validate input.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(void)	{

   char s[2] = { 0 }, *p;

   do {

      printf("A(AM) or P(PM): ");
      fgets(s, sizeof s, stdin);

      if((p = strchr(s, '\n')) == NULL) {
         while(getchar() != '\n'){} // eat the buffer
      }

   } while(toupper(s[0]) != 'A' && toupper(s[0]) != 'P');   
	 
   return (0);
}


HTH



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.