3

这应该只接受字母,但还不正确:

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

int main()
{
    std::string line;
    double d;

    while (std::getline(std::cin, line))
    {
        std::stringstream ss(line);
        if (ss >> d == false && line != "") //false because can convert to double
        {
            std::cout << "its characters!" << std::endl;
            break;
        }
        std::cout << "Error!" << std::endl;
    }
    return 0; 
}



这是输出:

567
Error!

Error!
678fgh
Error!
567fgh678
Error!
fhg687
its characters!
Press any key to continue . . .

fhg687由于字符串中的数字,应该输出错误。

接受的输出应仅包含字母,例如ghggjh.

4

3 回答 3

12

std::all_of使用适当的谓词在字符串上使用会好得多。在您的情况下,该谓词将是std::isalpha. (标题<algorithm><cctype>必需)

if (std::all_of(begin(line), end(line), std::isalpha))
{
    std::cout << "its characters!" << std::endl;
    break;
}
std::cout << "Error!" << std::endl;
于 2012-12-08T16:30:32.510 回答
7

更新:显示更完整的解决方案。

最简单的方法可能是遍历输入中的每个字符并检查该字符是否在 ascii 中的英文字母范围内(上 + 下):

char c;

while (std::getline(std::cin, line))
{
    // Iterate through the string one letter at a time.
    for (int i = 0; i < line.length(); i++) {

        c = line.at(i);         // Get a char from string

        // if it's NOT within these bounds, then it's not a character
        if (! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) ) {

             std::cout << "Error!" << std::endl;

             // you can probably just return here as soon as you
             // find a non-letter char, but it's up to you to
             // decide how you want to handle it exactly
             return 1;
        }
     }
 }
于 2012-12-08T16:30:32.807 回答
2

您还可以使用正则表达式,如果您需要更大的灵活性,这可能会派上用场。

对于这个问题,本杰明的回答是完美的,但作为参考,这就是正则表达式的使用方式(注意这regex也是 C++11 标准的一部分):

boost::regex r("[a-zA-Z]+");  // At least one character in a-z or A-Z ranges
bool match = boost::regex_match(string, r);
if (match)
    std::cout << "it's characters!" << std::endl;
else
    std::cout << "Error!" << std::endl;

如果string仅包含字母字符且至少包含一个字符(the +),match则为true

要求:

  • 随着升压:<boost/regex.hpp>-lboost_regex.
  • 使用C++11 : <regex>.
于 2012-12-08T17:09:23.450 回答