C ++ String与Int比较

时间:2014-11-12 13:42:46

标签: c++ string

我有以下问题:

do
{
    cout << "Type in something nice: ";
    getline(cin,test);
}
while (test.empty());

如果输入为空,则此代码段将检查输入。 如果它为空,则会重复相同的查询。

现在我要添加函数,字符串“test”必须介于0到100之间。 如何将字符串与静态int值进行比较?

stoi函数在这里不起作用,因为我必须使用非c ++ 11编译器

2 个答案:

答案 0 :(得分:1)

您必须将字符串转换为int: -

int b = atoi(a.c_str());

然后在确保转换成功后检查b是否介于0和100之间。

答案 1 :(得分:0)

do
{
    cout << "Type in something nice: ";
    getline(cin,test);
}
while (test.empty() && 0 > stoi(test) && stoi(test) < 100);

Function Stoi将String转换为Integer

相关问题