User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 422,531 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 4,877 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser: Programming Forums

error checking of user input

Join Date: Sep 2004
Posts: 6,297
Reputation: Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of 
Rep Power: 28
Solved Threads: 455
Super Moderator
Narue's Avatar
Narue Narue is offline Offline
Expert Meanie

Re: error checking of user input

  #3  
Apr 16th, 2005
>I want to ensure that the user puts in a name with characters and not use numbers.
Why? Numbers would be a valid string, and forcing your players to enter alphabetic characters may be an unnecessary restriction. Especially since it requires more work and code from you, and therefore more debugging and possible errors.

However, to do it you can use the standard library:
#include <algorithm>
#include <cctype>
#include <cstring>
#include <functional>
#include <iostream>

using namespace std;

int alpha ( int c )
{
  return isalpha ( c );
}

void getname ( char s[], int n )
{
  while ( cin.getline ( s, n )
    && *find_if ( s, s + strlen ( s ), not1 ( ptr_fun ( alpha ) ) ) != '\0' )
  {
    cout<<"No digits allowed. Try again: ";
  }
}
Though it's a little awkward using C-style strings. If you were using std::strings then it would be much easier:
#include <iostream>
#include <string>

using namespace std;

void getname ( string& s )
{
  while ( getline ( cin, s )
    && s.find_first_of ( "0123456789" ) != string::npos )
  {
    cout<<"No digits allowed. Try again: ";
  }
}
To do it manually you can use isalpha in a loop (a C-style solution), but the code is longer and harder to get right:
#include <cctype>
#include <iostream>

using namespace std;

void getname ( char s[], int n )
{
  while ( cin.getline ( s, n ) ) {
    char *p = s;

    while ( *p != '\0' ) {
      if ( !isalpha ( *p ) ) {
        cout<<"No digits allowed. Try again: ";
        break;
      }

      ++p;
    }

    if ( *p == '\0' )
      break;
  }
}
I'm a programmer. My attitude starts with arrogance, holds steady at condescension, and ends with hostility. Get used to it.
Reply With Quote  
All times are GMT -4. The time now is 12:12 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC