【问题标题】:How to check a string if a string has only alphabetical characters in C++如果字符串在C ++中只有字母字符,如何检查字符串
【发布时间】:2017-12-25 13:05:08
【问题描述】:

我正在为作业编写程序。部分原因是我需要验证某个字符串,所以它只包含字母字符,但我无法弄清楚。 这是我用来编写验证器的测试代码。

#include <cstring>
#include <iostream>
#include <string>

using namespace std;
bool isValidName(string str);
string str[20];

main() {
  cout << "enter name\n ";
  getline(cin, str[1]);
  isValidName(str[1]);
  cout << isValidName << endl;
  system("pause");
}

bool isValidName(string str) {
  for (int i = 0; i < (int)str.length(); i++) {
    if (!isalpha(str[i])) {
      return false;
      break;
    }
    return true;
    break;
  }
}

不管我放什么字符,它都会返回1 :o(

(感谢 Paul Rooney 修复缩进)

【问题讨论】:

  • 当你编译和运行这个程序时会发生什么?实际结果与您想要的结果有何不同?
  • 您还应该修复代码的缩进。除了缩进所需的任何空格外,每一行的开头都应该有额外的四个空格。当您复制和粘贴代码时,您可以突出显示它并按下 Ctrl-K 以自动插入这些额外的空格。
  • 提示:string str[20] 不是一个二十个字符的字符串,它是一个由二十个字符串组成的数组。数组也是零索引的,所以str[0] 是第一个条目。
  • 您的breaks 是多余的。它们出现在返回语句之后。还要考虑在检查只有第一个字符 isalpha 之后是否要返回 true。
  • 感谢大家的cmets! @tadman 我放了 str[20] 因为我想要一个字符串数组,但我只在一个上测试验证。

标签: c++ string boolean


【解决方案1】:

其中一个问题是您没有打印函数的返回值,而是打印了函数变量。 cout

你也已经在第一个字符检查中返回,希望下面的代码可以帮助你

#include <iostream>
#include <string>
#include <cstring>

using namespace std;
bool isValidName(string str);
string str;

main(){
    cout << "enter name\n ";
    getline(cin, str);
    cout << isValidName(str) << endl;
}

bool isValidName(string str) {
    for(int i=0;i<(int)str.length();i++) {
        if (!isalpha(str[i])) {
            return false;     
        }
    }
    return true;
}

感谢鲁尼修复

【讨论】:

  • 很高兴能帮上忙。感谢您选择我的答案。
【解决方案2】:

另一种编写验证过程的方式是:

bool isValidName(const std::string& str) 
{
    return std::all_of(str.begin(), str.end(), isalpha);
}

在你的函数中:

bool isValidName(string str) 
{
    for(int i=0;i<(int)str.length();i++) 
    {
        if (!isalpha(str[i])) 
        {
            return false;
            break;               // breaking here is useless, you've already returned.
        }
        return true;            // this is not in the right spot.  you return true
                                // if the first character is alpha !!
    }

    return true;               // <-- should be here.
}

适当的缩进使这些错误很容易被发现。

【讨论】:

  • 非常感谢!除了其他答案之外,这还帮助了我。我还了解到我真的必须处理我的缩进(无论是在我的代码中还是在发布问题时,因为帖子中的缩进与我的代码中的不同)
  • 请查看 c++ 做同样事情的方式,这使您的验证成为单行。
  • 最好把STL方案放在第一位。
【解决方案3】:

另一个优雅的解决方案是使用正则表达式来验证您的输入。

#include <iostream>
#include <string>
#include <regex>

bool isValidName(const std::string& str)
{
    if (std::regex_match(str, std::regex("[[:alpha:]]*")))
        return true;
    return false;
}

int main()
{
    std::string s("aaASd");
    std::cout << isValidName(s) << std::endl;
    std::string s1("ss23d");
    std::cout << isValidName(s1) << std::endl;

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2011-12-24
    • 2019-06-08
    • 2011-08-16
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多