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

正規表現を使用することもできます。これは、柔軟性が必要な場合に便利です。

この質問については、Benjaminの回答は完璧ですが、参考として、これが正規表現の使用方法です(regexC ++ 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アルファベット文字のみが含まれ、そのうちの少なくとも1つ(+)が含まれている場合は、matchですtrue

要件:

  • ブースト<boost/regex.hpp>付き:と-lboost_regex
  • C ++ 11の場合:<regex>
于 2012-12-08T17:09:23.450 に答える