0

嗨,我想从一个函数中保存许多不同的 csv 文件,这些文件具有基于不同双精度值的命名约定。我使用 for 循环执行此操作并传递一个字符串值以不同方式保存每个 .csv 文件。下面是我正在尝试做的一个例子,期望的结果是

1.1_file.csv
1.2_file.csv

但相反我得到

1.1_file.csv
1.11.2_file.csv

这是一个工作示例代码,我该怎么做才能解决这个问题

#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;
}
4

2 回答 2

1

ostringstream不会在循环的每次迭代中重置,因此您只需在每次迭代中添加它x;将其放在 的范围内,for以便os在每次迭代时成为不同的干净对象,或使用 . 重置内容os.str("")

此外,该变量s是不必要的;你可以做

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

而且您不需要s并且消除了制作字符串副本的开销。

于 2012-09-24T02:57:54.150 回答
1

您的 ostringstream 会为循环的每次迭代附加。您应该清除它并重用它,如下所示(礼貌:如何重用 ostringstream?关于如何重用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;
}
于 2012-09-24T02:59:29.210 回答