验证字符串在C ++中只包含字母 [英] Verifying that a string contains only letters in C++

查看:146
本文介绍了验证字符串在C ++中只包含字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只使用C#找到关于此主题的信息,我使用C ++。

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

int main()
{
//变量
string NombreJugador;

/ *内容
----------------------------------- ------------------------------------- * /
do
{
cout<< 你的名字: ;
cin>> NombreJugador;
} while(ValidarNombreJugador(NombreJugador));

return 0;
}

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

Numero = atoi(NombreJugador.c_str());

if(Numero!= 0)
{
cout< 没有绒毛ingresar数字,solo letras。 << endl;
return 1;
}

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



我在Google上找到了这种方式来验证



问题是,如果输入0,它会将其识别为字母,平均值,并返回true。 p>

我应该怎么做才能正确验证字符串只有字母而不是数字?



我是新的使用字符串的方式。

解决方案

没有数字:

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

/ p>

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


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.

解决方案

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
}

这篇关于验证字符串在C ++中只包含字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆