Home > Mobile >  How to only accept character on c
How to only accept character on c

Time:05-19

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.

CodePudding user response:

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;
        }
    }
}

CodePudding user response:

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;

  •  Tags:  
  • c
  • Related