我正在编写一个程序,我需要获取一行输入,其中包含一个字母和两个数字,中间有空格。比方说,类似于“I 5 6”。
我使用 std::getline 将输入作为字符串获取,因此空格不会有任何问题,然后使用 for 循环浏览字符串中的各个字符。只有当第 2 个和第 3 个字符(第 3 个和第 5 个计算空格)是数字时,我才需要执行特定条件。
如何测试字符串中某个位置的字符是否为 int?
最佳答案
为了您的目的,我会将此行放入 std::istringstream
并使用普通的流提取运算符从中获取值。
也许是这样的
char c;
int i1, i2;
std::istringstream oss(line); // line is the std::string you read into with std::getline
if (oss >> c >> i1 >> i2)
{
// All read perfectly fine
}
else
{
// There was an error parsing the input
}
关于c++ - 测试字符串 vector 中的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763478/