从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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短