从C ++中的字符串中提取所有整数
在这里,我们将看到如何从C++中的字符串中提取所有整数。我们可以在存在数字和无数字的地方放置一个字符串。我们将从中提取所有数值。
为了解决这个问题,我们将在C++中使用stringstream类。我们将逐字切割字符串,然后尝试将其转换为整数类型数据。如果转换完成,则为整数并输出值。
Input: A string with some numbers “Hello 112 World 35 75” Output: 112 35 75
算法
Step 1:Take a number string Step 2: Divide it into different words Step 3: If a word can be converted into integer type data, then it is printed Step 4: End
范例程式码
#include<iostream>
#include<sstream>
using namespace std;
void getNumberFromString(string s) {
stringstream str_strm;
str_strm << s; //convert the string s into stringstream
string temp_str;
int temp_int;
while(!str_strm.eof()) {
str_strm >> temp_str; //take words into temp_str one by one
if(stringstream(temp_str) >> temp_int) { //try to convert string to int
cout << temp_int << " ";
}
temp_str = ""; //clear temp string
}
}
main() {
string my_str = "Hello 112 World 35 75";
getNumberFromString(my_str);
}输出结果
112 35 75
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短