功能
從name中找出全部數值字符,之后將name(string類)轉為d(double類)
代碼
#include <iostream>
#include <list>
#include <deque>
#include <vector>
#include <forward_list>
#include <array>
using namespace std;int main()
{string name("zhang2021.5san4.2");string numbers("+-.0123456789");double d; // string要轉換為doubleunsigned pos = 0; // 從下標0開始搜索數值字符string over; // 存儲數值字符的stringwhile ((pos = name.find_first_of(numbers, pos)) != string::npos) {string s; // 存儲每一次循環搜出來的數值字符s = name.substr(pos); // 將數值字符起始位置到整體末尾的字符生成子串auto pos1 = s.find_first_not_of(numbers);// 從非數值字符位置結束if(pos1 != string::npos){over.append(name.substr(pos, pos1));pos += pos1;}else{ // 可能會有以數值字符結束的字符// 因此僅以上面的非數值字符結束是不夠的// 還需要以最后出現的數值字符作為結尾auto pos2 = s.find_last_of(numbers)+1;over.append(name.substr(pos, pos2));pos += pos2;}cout << over << endl; // 調試的一部分//用來觀察每次循環結束的存儲數值字符的string的值}d = stod(over); // 將存儲數值字符的string轉化為doublecout << d << endl;return 0;
}