C++ 只收信件
这应该只接受信件,但它还不正确:C++ 只收信件,c++,std,C++,Std,这应该只接受信件,但它还不正确: #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);
#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;
}
由于字符串中的数字,fhg687
应输出错误
接受的输出应该只包含字母,例如
ghggjh
您最好在字符串上使用std::all_of
,并使用适当的谓词。在您的例子中,该谓词将是std::isalpha
。(需要标题
和
)
if(std::all_of(begin(line)、end(line)、std::isalpha))
{
标准::cout更新:以显示更完整的解决方案
最简单的方法可能是迭代输入中的每个字符,并检查该字符是否在(上限+下限)内:
charc;
while(std::getline(std::cin,line))
{
//一次遍历字符串一个字母。
对于(int i=0;i 如果(!((c>='a'&&c='a'&&c您也可以使用正则表达式,如果您需要更大的灵活性,它可能会派上用场
对于这个问题,Benjamin的答案是完美的,但作为参考,这就是如何使用regex(注意,regex
也是C++11标准的一部分):
boost::regex r(“[a-zA-Z]+”);//在a-Z或a-Z范围内至少有一个字符
bool match=boost::regex_匹配(字符串,r);
如果(匹配)
std::你的意思是只按字母顺序排列的字符,还是它也应该接受标点符号之类的东西?是的,只按字母顺序排列。不!,@,等等。在这种情况下,这几乎等同于几个。主要的变化是用isalpha
替换isdigit
。是的,你是正确的。前面的问题要求数字。有还有std::isalpha()
@Cornstalks哦,太好了!我在读本杰明的答案时看到了这一点-今天学到了一些新东西=)@sampson chen您能在这里检查我的代码吗?即使我做了更改,fhg687
仍然是一个字符
。谢谢。@sg552:问题是您没有遍历字符串中的字符(意思是:每次查看一个字符)。请参阅我更新的答案,以获得更全面的解决方案,以了解您需要更改的内容。行
已经是一个字符串,那么为什么不直接使用它并完全删除stringstream
?+1;在谷歌上搜索了一段时间,这似乎是我必须使用的最干净的解决方案::isalpha
567
Error!
Error!
678fgh
Error!
567fgh678
Error!
fhg687
its characters!
Press any key to continue . . .
if (std::all_of(begin(line), end(line), std::isalpha))
{
std::cout << "its characters!" << std::endl;
break;
}
std::cout << "Error!" << std::endl;
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;
}
}
}
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;