我在搜索字符串时遇到麻烦,如果我输入仅包含字母的单词,它可以按需工作,虽然代码可以工作,但是当我在工作中添加数字时,代码也可以工作,仅当我的var仅包含字母并且可以找到数字或符号时才可以接受以代码开头的代码?


#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
    label:
    string var1 = "";
cout << "Enter a word: ";
cin >> var1;
    for (int i = 0; i < var1.size (); i++)
    {
        int uppercaseCHar = toupper (var1[i]);
        if (uppercaseCHar < 'A' || uppercaseCHar > 'Z')
        {
            goto endloop;
            cout << endl;

        } else
            goto label;
            cout << endl;

       }
     endloop:
     cout << "Yout word contains only letters";

    }




Output:
Enter a word: work
Enter a word: wro1
Enter a word: 123
Yout word contains only letters

最佳答案

这是使用std::all_of的解决方案:

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>

int main()
{
    bool isAllLetters = false;
    do
    {
        std::string var1;
        std::cout << "Enter a word: ";
        std::cin >> var1;

        // check if all characters are letters
        isAllLetters = std::all_of(var1.begin(), var1.end(), [](char ch)
                                  { return std::isalpha(static_cast<unsigned char>(ch));});

        if ( isAllLetters )
           std::cout << "Your word contains only letters\n";
        else
           std::cout << "Your word contains stuff other than letters\n"
    } while ( !isAllLetters );
}

08-06 00:36