【问题标题】:How to create multiple files using c++ [duplicate]如何使用c ++创建多个文件[重复]
【发布时间】:2017-04-19 18:15:54
【问题描述】:

在 c++ 中使用 for 循环创建多个文件。

目标:- 在分别命名为 1.txt2.txt3 的文件夹中创建多个文件。 txt

这是我的示例代码:

int co = 3;
for (int i = 1; i <= co; i++)
{   
    ofstream file;
    file.open (i+".txt");
    file.close();
}

此代码创建三个文件:t、xt 和 txt。

这段代码发生了什么?和 我的代码有什么问题?

【问题讨论】:

  • 你必须先将 i 转换成字符串。
  • 尝试将您的 i 变量转换为字符串。
  • 习语i+".txt" 就像".txt" 是一个数组 一样工作,因此您会得到该字符串的ith 字符的偏移量。因此,txt(偏移量 1)、xt(偏移量 2)和 t(偏移量 3)。
  • Dupe 正在回答您问题正文中的问题。有关可行的替代方案,请参阅下面的答案,stackoverflow.com/questions/64782/… 或更容易通过搜索网络找到。
  • 谢谢,还有一个问题,为什么它会创建名为 t、xt 和 txt 的文件

标签: c++


【解决方案1】:

您需要将i转换为字符串,以便使用operator+连接它,否则您会无意中执行pointer arithmetic

// C++11
#include <fstream>
#include <string>     // to use std::string, std::to_string() and "+" operator acting on strings 

int co = 3;
for (int i = 1; i <= co; i++)
{   
    ofstream file;
    file.open (std::to_string(i) + ".txt");
    file.close();
}

如果您无权访问 C++11(或者如果您想避免显式“转换 i 然后连接”),您可以使用 std::ostringstream

// C++03
#include <fstream>
#include <sstream>

std::ostringstream oss;
int co = 3;
for (int i = 1; i <= co; i++)
{   
    ofstream file;

    oss << i << ".txt"; // `i` is automatically converted
    file.open (oss.str()); 
    oss.str(""); // clear `oss`

    file.close();
}

注意: clang++ 使用 -Wstring-plus-int 警告标志 (wandbox example) 捕获此错误。

【讨论】:

  • 你错了。首先".txt" 不是std::string。其次int + char* 的定义非常明确:它移动指针。这就是为什么 OP 在每次迭代中都会获得 .txt 文件名的片段。
  • @freakish:谢谢,已修复。我已经习惯了 "..."s 字面量,我猜 :(
  • 同样在 clang++ 的情况下,-Wstring-plus-int 似乎总是显示这个警告,不管i 是什么。至少这是我观察到的,但不确定。
  • @freakish:是的,但前提是在编译时整数值未知。无论如何,我都会更改注释 - 我的评论可能具有误导性。
【解决方案2】:

在 C++ 中,您不能简单地将字符串文字与整数“连接”。字符串文字将分解为指向常量 char (char const *) 的指针,并应用指针算术规则。

当从一个指针中添加或减去一个整数值时,结果是一个指向一个对象的指针,该对象是内存中元素的数量 - 当然,这只有在没有跨越该内存的边界时才成立。

【讨论】:

    【解决方案3】:

    您必须先将i 转换为std::string

    int co = 3;
    for (int i = 1; i <= co; i++){   
        ofstream file;
        file.open (std::to_string(i) + ".txt"); //Here
        file.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 2016-08-15
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多