本文介绍了只接受字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This should accept only letters, but it is not yet correct:

#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;
}




这是输出: / p>



Here is the output:

567
Error!

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

fhg687

接受的输出只能包含字母,例如 ghggjh

Accepted output should contain letters only, such as ghggjh.

推荐答案

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

Updated: to show a fuller solution.

方法可能是遍历输入中的每个字符,并检查该字符是否位于 ascii中的英文字母范围(upper + lower):

The simplest approach would probably be to iterate through each char in the input and check whether that char is within English-letter ranges in ascii (upper + lower):

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;
        }
     }
 }

这篇关于只接受字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:32