1

How do I go about checking the user input that was stored into an std::string to be valid such that it should only contain all letters, no numbers or symbols?

std::string name;
std::cout << "Hello, enter your name:\n";
std::cin >> name;
//check if the name was entered correctly after user input

Should I be using regex? If so, how should I be using it effectively?

JeJo
  • 30,635
  • 6
  • 49
  • 88
ferics
  • 77
  • 7
  • Names can contain digits BTW: [falsehoods-programmers-believe-about-names-with-examples](https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/). – Jarod42 May 17 '19 at 10:53

2 Answers2

3

Should I be using regex?

No. You do not need that here.

Simply use the algorithm function std::all_of check all the alphabets in the string wether std::isalpha.

std::all_of(std::begin(name), std::end(name),
           [](const char alphabet) noexcept -> bool { return std::isalpha(alphabet); });

complete example code would look like: (See Live)

#include <iostream>
#include <string>
#include <algorithm> // std::all_of
#include <cctype>    // std::isalpha

int main()
{
    std::string name;
    std::cin >> name;
    std::cout << std::boolalpha << std::all_of(std::begin(name), std::end(name),
        [](const char alphabet) noexcept -> bool { return std::isalpha(alphabet); });
    return 0;
}

sample input: iamnumber4

output: false

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • Is there an alternative? I had just checked the requirement of my software specification and it does not allow to use header apparently. – ferics May 17 '19 at 10:20
  • hi @JeJo, I had gone to use regex and it has been working perfectly for "^[a-zA-Z]+\\s?+[a-zA-Z]+$" but do you have any idea why this regex still return true for "John Smith" (there are two whitespaces between John and Smith) when it should ONLY return true when there's zero or one of whitespace? It's currently driving me insane. PS: I tried to comment John Smith with two whitespaces but stackoverflow trims down to one :( – ferics May 17 '19 at 12:59
  • 1
    thanks for getting back. actually I figured out the reason why it stilled returned true. That's because the correct regex for one whitespace between the two words is "^[a-zA-Z]+\\s?[a-zA-Z]+$" not "^[a-zA-Z]+\\s?[a-zA-Z]+$". thanks though!! – ferics May 19 '19 at 13:37
  • @ChanbothSomSince you found your answer your own, you could write it as an answer for the future readers of this question and accept it by yourself. – JeJo May 19 '19 at 14:27
  • sure, will do. thanks! – ferics May 19 '19 at 14:27
  • my question was marked as duplicate so I can no longer post an answer and select it as so. – ferics May 21 '19 at 08:04
0

You can use std::regex to check if the input is good
You can also make your own function checking for each caracter of name if there is only numbers.