Replacing doubles in string with another double

Take this string for an example,

"asdf 9.000 1.232 9.00 23.1 545.3"

Is there a way to replace any of the doubles with another double?

Example: Replace the first "9.000" with a "10.0".

Any tips on how to do this?

EDIT: I am aware that string::replace will do the trick, but how do I make it work for arbitrary cases? By arbitrary I mean that I don't know the size of the string to be replaced, I just want to be able to replace any number with a given number.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>

int main() 
{ 
    const std::string input = "asdf 9.000 1.232 9.00 23.1 545.3" ;
    std::cout << input << '\n' ;
    
    // create an input string stream to read from the string
    std::istringstream stm(input) ;
    
    // read the first string
    std::string first ;
    stm >> first ;
    
    // read the  numbers into a vector
    std::vector<double> numbers ;
    double n ;
    while( stm >> n ) numbers.push_back(n) ;
    
    // modify the numbers
    for( double& d : numbers ) d += 1.0 ;
    
    // recreate the string with the modified numbers
    std::ostringstream ostm ;
    ostm << first << std::fixed << std::setprecision(3) ;
    for( double& d : numbers ) ostm << ' '  << d ;

    std::string result = ostm.str() ;
    std::cout << result << '\n' ;
}

http://coliru.stacked-crooked.com/a/8b93e064b1e93b65
Topic archived. No new replies allowed.