这应该只接受字母,但它还不正确:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
567
Error!
Error!
678fgh
Error!
567fgh678
Error!
fhg687
its characters!
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
fhg687 应该输出错误,因为字符串中的数字.
接受的输出应仅包含字母,例如ghggjh.
Ben*_*ley 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;
Run Code Online (Sandbox Code Playgroud)
更新:显示更全面的解决方案.
最简单的方法可能是迭代输入中的每个char并检查该char是否在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)