问题
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;
}
Here is the output:
567
Error!
Error!
678fgh
Error!
567fgh678
Error!
fhg687
its characters!
Press any key to continue . . .
fhg687
should output error because of the numbers in the string.
Accepted output should contain letters only, such as ghggjh
.
回答1:
Updated: to show a fuller solution.
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;
}
}
}
回答2:
You'd be much better off using std::all_of
on the string, with an appropriate predicate. In your case, that predicate would be std::isalpha
. (headers <algorithm>
and <cctype>
required)
if (std::all_of(begin(line), end(line), std::isalpha))
{
std::cout << "its characters!" << std::endl;
break;
}
std::cout << "Error!" << std::endl;
回答3:
You can also use regular expressions, which may come in handy if you need more flexibility.
For this question, Benjamin answer is perfect, but just as a reference, this is how regex could be used (notice that regex
is also part of the C++11 standard):
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;
If string
contains only alphabetic characters and at least one of them (the +
), then match
is true
.
Requirements:
- With boost:
<boost/regex.hpp>
and-lboost_regex
. - With C++11:
<regex>
.
来源:https://stackoverflow.com/questions/13779321/accept-only-letters