加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 只接受信件

发布时间:2020-12-16 10:51:09 所属栏目:百科 来源:网络整理
导读:这应该只接受字母,但它还不正确: #include iostream#include string#include sstreamusing namespace std;int main(){ std::string line; double d; while (std::getline(std::cin,line)) { std::stringstream ss(line); if (ss d == false line != "") //f
这应该只接受字母,但它还不正确:

#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.

解决方法

更新:显示更全面的解决方案.

最简单的方法可能是迭代输入中的每个字符,并检查该字符是否在English-letter ranges in 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;
        }
     }
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读