【问题标题】:C++ fstream - How to add variable in .open() instead of string?C++ fstream - 如何在 .open() 中添加变量而不是字符串?
【发布时间】:2015-09-18 07:14:07
【问题描述】:

我正在尝试编写一个程序,该程序将在循环内的文件夹中创建/输出多个文件,但给我错误。这样的事情可能吗?一直在寻找没有运气。谢谢! 这是一个例子:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream text;
    for(int i = 0; i < 100; i++);
    {
        text.open("folder/" + i + ".txt");
        text << "This is text file #" << i << "."<< endl;
        text.close();
    }
return 0;
}

【问题讨论】:

  • std::string file_path = std::string("folder/") + std::to_string(i) + ".txt"
  • std::to_string 给出错误? :(
  • 使用-std=c++11 标志编译。

标签: c++ string variables fstream ofstream


【解决方案1】:

您正在尝试添加const char *number,这是不可能的。这不是你想要的。相反,您应该在循环中执行以下操作

ofstream text;
for(int i = 0; i < 100; i++);
{
    string str;
    str = "folder/";

    std::stringstream ss;
    ss << i; //convert int to stringstream

    str += ss.str(); //convert stringstream to string 
    str + =  ".txt";

    text.open(str); //use final string
    text << "This is text file #" << i << "."<< endl;
    text.close();
} 

不要忘记包含#include &lt;sstream&gt;

【讨论】:

  • 我认为 std::stringstream` 用于一个 int 数字而不是 std::to_string 有点矫枉过正。
  • @Satus 其实我读到了上面的评论。不确定 to_string 是否适用于 C++ 98。因为很多人还没有开始使用 C++ 11/14。
  • 它不适用于 C++98。但是,好吧,在 2015 年没有理由不使用 C++11。
  • @Satus 完全同意。但只是想与很多程序员保持联系。但是根据新的 C++ 标准,您的解决方案更准确。
  • @VardanBetikyan 很高兴为您提供帮助。
【解决方案2】:

你不能连接一个简单的字符串并将一个数字 int 字符串转换为 写作

  "folder/" + i + ".txt";

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream text;
    for(int i = 0; i < 100; i++);
    {
        stringstream FileName;
        FileName<<"folder/"<<i<<".txt;
        text.open(FileName.str().c_str());
        text << "This is text file #" << i << "."<< endl;
        text.close();
    }
    return 0;
 }

我已经在循环中创建了字符串流。 这样做会在每个循环中创建一个新的字符串流,并在循环结束时销毁 当您在循环之外声明字符串流时,同样会起作用。 但是这种情况下,您在每个循环结束时都清除了 stringstreeam

【讨论】:

  • 字符串流之后的“文件名”给我一个错误:((红线)
  • 当你尝试编译时编译器会告诉你什么?
猜你喜欢
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多