how to test a string for letters only

后端 未结 6 523
盖世英雄少女心
盖世英雄少女心 2020-11-27 16:58

how could I test a string against only valid characters like letters a-z?...

string name;

cout << \"Enter your name\"
cin >> name;

string lette         


        
6条回答
  •  一生所求
    2020-11-27 17:34

    STL way:

    struct TestFunctor
    {
      bool stringIsCorrect;
      TestFunctor()
      :stringIsCorrect(true)
      {}
    
      void operator() (char ch)
      {
        if(stringIsCorrect && !((ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A')))
          stringIsCorrect = false;
      }
    }
    
    TestFunctor functor;
    
    for_each(name.begin(), name.end(), functor);
    
    if(functor.stringIsCorrect)
      cout << "Yay";
    

提交回复
热议问题