1

I only found information about this topic using C#, and i'm using C++. Hope you can help me with this.

My code:

#include <iostream>
#include <fstream>  // Librería para el manejo de archivos
#include <string>   // Librería para el manejo de strings
#include <stdlib.h> // Librería para el uso de system("cls");

int main()
{
    //Variables
    string NombreJugador;

/*  Content
------------------------------------------------------------------------*/
    do
    {
        cout << "Your name: ";
        cin >> NombreJugador;
    } while(ValidarNombreJugador(NombreJugador));

    return 0;
}

/*  Function
------------------------------------------------------------------------*/
int ValidarNombreJugador(string NombreJugador)
{
    int Numero;

    Numero = atoi(NombreJugador.c_str());

    if (Numero!=0)
    {
        cout << "No puede ingresar numeros, solo letras." << endl;
        return 1;
    }

    else
    {
        cout << "Perfecto, tu nombre no tiene numeros." << endl;
        return 0;
    }
}

I have found on Google this way to validate that the name only have letters and not numbers.

The problem is that if you enter "0", it recognize it as a letter, a mean, it returns true.

What should I do to properly validate that the string has only letters and not numbers?.

I'm new using string by the way.

  • you also tested only that your input not start with numbers, if it contains numbers in the middle or at the end it pass your test. – SHR Nov 04 '15 at 21:48
  • 1
    "Only letters" and "no numbers" are different things. Which one do you actually want to test for? – T.C. Nov 04 '15 at 21:51

1 Answers1

8

No numbers:

if(std::none_of(str.begin(), str.end(), [](unsigned char c){return std::isdigit(c);})) {
    // stuff
}

All letters:

if(std::all_of(str.begin(), str.end(), [](unsigned char c){return std::isalpha(c);})) {
    // stuff
}
T.C.
  • 133,968
  • 17
  • 288
  • 421