0

Hi i want to save many different csv files from a function with a naming convention based on a different double value. I do this with a for loop and pass a string value to save each .csv file differently. Below is an example of what I'm trying to do the desired result would be

1.1_file.csv
1.2_file.csv

but instead i get

1.1_file.csv
1.11.2_file.csv

Here is a working sample code, what can i do to fix this

#include <sstream>
#include <iomanip>
#include <cmath>
#include <iostream>
#include <vector>

int main(){
    std::string file = "_file.csv";
    std::string s;
    std::ostringstream os;
    double x;

    for(int i = 0; i < 10; i++){
        x = 0.1 + 0.1 *i;
        os << std::fixed << std::setprecision(1);
        os << x;
        s = os.str();
        std::cout<<s+file<<std::endl;
        s.clear();
    }

    return 0;
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
pyCthon
  • 11,746
  • 20
  • 73
  • 135

2 Answers2

1

The ostringstream doesn't reset on each iteration of the loop, so you are just adding x to it every iteration; put it inside the scope of the for to make os be a different clean object on each iteration, or reset the contents with os.str("").

Also, the variable s is unnecessary; you can just do

std::cout << os.str() + file << std::endl;

And you don't need s and you eliminate the overhead of making a copy of the string.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
1

Your ostringstream is getting appended for each iteration of the loop. You should clear it and reuse it as shown below (courtesy: How to reuse an ostringstream? on how to reuse an ostringstream)

#include <sstream>
#include <iomanip>
#include <cmath>
#include <iostream>
#include <vector>

int main() {

    std::string file = "_file.csv";
    std::string s;

    double x;
    std::ostringstream os;

    for (int i = 0; i < 10; i++) {

        x = 0.1 + 0.1 * i;
        os << std::fixed << std::setprecision(1);
        os << x;
        s = os.str();
        std::cout << s + file << std::endl;
        os.clear();
        os.str("");
    }

    return 0;
}
Community
  • 1
  • 1
Vikdor
  • 23,934
  • 10
  • 61
  • 84