2012-09-24 50 views
0

您好我想保存许多不同的csv文件从函数与基于不同的双重值的命名约定。我用for循环来做这件事,并传递一个字符串值以不同的方式保存每个.csv文件。下面是我想要做的期望的结果将是错误与std :: ostringsteam和std :: string

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; 
} 
+0

什么的随机downvote? – pyCthon

回答

1

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

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

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

而且你不需要s和你消除使字符串的副本的开销。

1

您的ostringstream正在追加循环的每次迭代。你应该清楚并重复使用如下图所示(礼貌:如何重用ostringstreamHow 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; 
} 
+0

@SethCarnegie,可能是,我只是试图传达'os'应该是'for'循环的本地。 – Vikdor

+0

哦,是的,哎呀,我以为你加了它。我会删除我的评论。 –

相关问题