0

In my program, when the user is prompted for an employee's name, the system prompts him to re-enter his name if he enters a number or only a space. How do I put a requirement decision in parentheses in a while loop, here's my code.

std::string NAME;
std::cout << "Please enter the name: " << std::endl;
  std::cin >> NAME;
  while (NAME.length() == 0) {
    std::cout << "Your input is not correct. Please re-enter your name" << std::endl;
    std::cin >> NAME;
  }

I'm only going to restrict the input to not being empty, but I don't know how to get the user to only allow characters to enter.

Thank you all.

Xu Shuo ze
  • 113
  • 4
  • 1
    simply search for characters which are not allowed, if you find one or more, raise the error message. – Klaus May 19 '22 at 07:07
  • 1
    Consider using a RegEx expression to compare the input to valid patterns. – Remy Lebeau May 19 '22 at 07:24
  • 1
    Does this answer your question? [how to test a string for letters only](https://stackoverflow.com/questions/7616867/how-to-test-a-string-for-letters-only) – moooeeeep May 19 '22 at 07:25
  • Related: https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ – moooeeeep May 19 '22 at 07:27
  • @moooeeeep No, I do not want to use a function here. – Xu Shuo ze May 19 '22 at 07:30
  • 2
    Maybe you should clarify what you are actually asking about. Right now it is not really clear whether you are asking about the validation or the loop. Also, you should totally implement this as one or multiple functions. – moooeeeep May 19 '22 at 07:42

2 Answers2

1

You can use std::all_of on the string defined in algorithm header file. It should be used with appropriate predicate (isalpha for your case defined in cctype header file). Try this:

#include <iostream>
#include <algorithm>
#include <cctype>


int main()
{
    std::string NAME;
    std::cout << "Please enter the name: " << std::endl;

    while (std::getline(std::cin, NAME)) {
        if (NAME.length() == 0)
        {
            std::cout << "Your input is not correct. Please re-enter your name" << std::endl;
        }

        // This will check if the NAME contains only characters.
        else if (std::all_of(NAME.begin(), NAME.end(), isalpha))
        {
            break;
        }
        else {
            std::cout << "Only characters are allowed:" << std::endl;
        }
    }
}
Avinash
  • 875
  • 6
  • 20
-2

Every character has an ASCII code. Use an if condition to check if an input character falls between the ASCII codes for the English alphabets. ASCII Table. You can convert a character to its ASCII code by simply type-casting it as an integer.

Example: For a character array "ARR", having data: "apple"; doing the following will give you "97".

std::cout << (int)ARR[0] << std::endl;