如何从字符串C++读取多个整数
How To Read Multiple Integers from a String C++
我正在尝试了解如何从字符串转换多个整数。我尝试使用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
等检查所有字符是否都是数字。
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- Arduino从Txt读取整数
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从二进制文件中读取整数数组
- 如何从字符串C++读取多个整数
- 使用字符串流读取整数并将它们相加
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何使用字符和整数C 读取文件
- 从文件到短 /长整数读取字节
- do整数读取需要受到关键部分的保护
- 此项目不会将整数读取为二进制并将其作为二进制输出到新文件
- 将连续字节作为一个整数读取
- 如何将文件中的整数读取到动态数组中
- 如何将字符串读取为字符串向量或将整数读取为整数向量
- 将文件中的间隔整数读取到C++数组中
- 将文件中的整数读取到C++中的向量中
- 如何在C++中将空格和换行符分隔的整数读取到2D数组中
- 将一组整数读取为C++中的字符串
- 我如何得到多行字符串和整数读取和输入文件,并在c++中显示
- 通过无符号整数读取无符号字符数组未定义,因此不安全