检查它是否是整数

时间:2011-08-16 12:48:41

标签: c++ string

我遇到的问题是我必须从数据库中读取Integers。变量以Strings形式返回,可以是"""0""1""2""3"(这些是我的到目前为止看到了)。 因此,使用标准atoi函数无效,因为我无法区分"""0"

有人有一个很好的解决方案吗?

此致 斯蒂芬

修改

“”,“0”,“1”,“2”或“3”不是我到目前为止看到的唯一可能性......也有可能有人在现场写“Hello World”! !!

3 个答案:

答案 0 :(得分:3)

使用stringstream进行转换:

int main()
{
    std::stringstream tmp;
    tmp << ""; //This would be the string from the database
    int x;
    if (tmp >> x)
    {
        //We won't get here
        std::cout << x << std::endl;
    }

VS

int main()
{
    std::stringstream tmp;
    tmp << "0";
    int x;
    if (tmp >> x)
    {
        //Will output 0
        std::cout << x << std::endl;
    }

编辑:当有人输入“Hello World”

时,此代码处理此案例

答案 1 :(得分:1)

如果您的情况是性能问题,我建议如下:

解决方案1:

std::string input(<your string value>);
int val;
if (sscanf(input.c_str(), "%d", &val) != 1)
{
    cout << "it's empty/not an integer";
}
else
{
    cout << "val is:" << val;
}

解决方案2:

std::string input(<your string value>);
int val;
if(strcmp(input.c_str(), "") ==0)
{
    cout << "it's empty";
}
else
{
    val = atoi(input.c_str());
    cout << "val is:" << val;
}

我建议使用第一种解决方案,因为如果输入启动无效内容(不是整数),atoi解决方案将失败(失败时atoi返回0)。

虽然,如果你的值只能是“”,“0”,“1”,“2”,“3”,那么第二个解决方案也应该有效。

答案 2 :(得分:0)

一个条件很容易检查(""),因为它会导致为空。

其次,您可以删除引号,例如

std::string::find( '"' );

如果字符串中没有双引号或第一个字符串的索引,

将返回std::string::npos

std::string::erase( pos, npos );

相关问题