C++字符串与 int 进行比较

C++ String Compare with Int

本文关键字:比较 int 字符串 C++      更新时间:2023-10-16

我有以下问题:

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

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

现在我想添加一个函数,字符串"test"必须在 0 到 100 之间。如何将字符串与静态 int 值进行比较?

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

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

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

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

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

函数 Stoi 将字符串转换为整数