如何从字符串C++读取多个整数

How To Read Multiple Integers from a String C++

本文关键字:整数 读取 C++ 字符串      更新时间:2023-10-16

我正在尝试了解如何从字符串转换多个整数。我尝试使用atoi()stoi()istringstream(),它们都做同样的事情。我不能得到超过一个整数。

例如,如果字符串是"Chocolate and Milk 250 pounds and 2 oz or 1.5 coins."上述所有功能都不起作用。它不会占用整个字符串。如果我只留下一个数字,那么它将起作用。我希望能够读取整个字符串并获取所有整数(不是浮点数(。

我正在为字符串使用while(getline())。然后尝试将其放入字符串中。

虽然,如果我只能返回字符串中的整数总数,那就更好了。无论哪种方式,我都在尝试双向学习。在这种情况下,输出将是"2",因为只有两个 int。

一种方法是使用分隔符拆分字符串,并对单个字符串使用stoi来检查它们是否是整数。

#include <iostream>
#include <sstream>
#include <string>
int main(){
std::string s = "Chocolate and Milk 250 pounds and 2 oz or 1.5 coins.";
int count = 0;
std::istringstream iss(s);
std::string token;
while(getline(iss,token,' ')){
if(std::isdigit(token[0]) &&stoi(token) && token.find('.')==std::string::npos){
count++;
}
}
std::cout<<count<<std::endl;
}

请注意,如果stoi成功,则可以对字符串执行更复杂的检查,但输入不是有效的整数。您可以使用一个辅助函数,通过使用isdigit等检查所有字符是否都是数字。