8

显然,这应该用于显示字符串是否为数字,例如“12.5”==是,“abc”==否。但是,我对输入毫无顾忌。

std::stringstream ss("2");
double d; ss >> d;
if(ss.good()) {std::cout<<"number"<<std::endl;}
else {std::cout<<"other"<<std::endl;}
4

4 回答 4

7

不要使用好()!测试流是否失败

if (ss)

Good 告诉您是否设置了 eofbit、badbit 或 failbit,而 fail() 告诉您有关 badbit 和 failbit。你几乎从不关心 eofbit 除非你已经,因此您几乎从不想使用 good。

请注意,如上所述,直接测试流完全等同于:

if (!ss.fail())

相反,!ss 等价于 ss.fail()。


将提取组合到条件表达式中:

if (ss >> d) {/*...*/}

完全等同于:

ss >> d;
if (ss) {/*...*/}

但是,您可能想测试是否可以将完整的字符串转换为双精度,这有点复杂。使用已经处理所有情况的 boost::lexical_cast。

于 2011-02-07T00:50:08.067 回答
6

如果要检查 a 是否string包含一个数字而不包含其他任何内容(空格除外),请使用以下命令:

#include <sstream>

bool is_numeric (const std::string& str) {
    std::istringstream ss(str);
    double dbl;
    ss >> dbl;      // try to read the number
    ss >> std::ws;  // eat whitespace after number

    if (!ss.fail() && ss.eof()) {
        return true;  // is-a-number
    } else {
        return false; // not-a-number
    }
}

ss >> std::ws对于接受带有尾随空格的数字很重要,例如"24 ".

检查对于ss.eof()拒绝像"24 abc". 它确保我们在读取数字(和空格)后到达字符串的末尾。

测试线束:

#include <iostream>
#include <iomanip>

int main()
{
    std::string tests[8] = {
            "", "XYZ", "a26", "3.3a", "42 a", "764", " 132.0", "930 "
    };
    std::string is_a[2] = { "not a number", "is a number" };
    for (size_t i = 0; i < sizeof(tests)/sizeof(std::string); ++i) {
        std::cout << std::setw(8) << "'" + tests[i] + "'" << ": ";
        std::cout << is_a [is_numeric (tests[i])] << std::endl;
    }
}

输出:

      '': not a number
   'XYZ': not a number
   'a26': not a number
  '3.3a': not a number
  '42 a': not a number
   '764': is a number
' 132.0': is a number
  '930 ': is a number
于 2013-02-15T17:30:26.743 回答
4

您应该使用 anistringstream以便它知道它正在尝试解析输入。此外,只需直接检查提取结果,而不是good稍后使用。

#include <sstream>
#include <iostream>

int main()
{
    std::istringstream ss("2");
    double d = 0.0;
    if(ss >> d) {std::cout<<"number"<<std::endl;}
    else {std::cout<<"other"<<std::endl;}
}
于 2011-02-07T00:49:20.360 回答
-1
int str2int (const string &str) {
  stringstream ss(str);
  int num;
  if((ss >> num).fail())
  { 
      //ERROR: not a number
  }
  return num;
}
于 2011-02-07T00:56:04.663 回答