c++ - 在循环中创建多个文本文件

标签 c++ file

我想用 C++ 创建一些文本文件。例如:我将运行一个从 1 到 5 的循环并创建以下文件:

1.txt
2.txt
3.txt
4.txt
5.txt

这可能吗?我做了一个示例代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

main()
{
   FILE *fp;
    int i;
    for(i=1;i<=5;i++)
    {
        //fp=fopen("%d.txt","r",i); //what will go here??

 }
}

我对要在循环中写什么感到困惑。我怎样才能创建这些文件?

最佳答案

char i;
char fileName[] = "0.txt";
for(i='1';i<='5';i++)
{
   fileName[0]=i;
   fp=fopen(fileName,"r"); //what will go here??
   //...
}

如果这对您的情况来说太简单了,您可以使用 sprintf


既然你标记了 c++,我认为 fstream string 是要使用的东西。

一个简单的 C++ 例子

#include <fstream>
#include <string>
using namespace std;

int main(){
   string base(".txt");
   for(int i=1;i<=5;++i){
      ofstream(to_string(i)+base);// to_string() need c++11
   }
}

如果你仍然没有to_string(你没有c++11或者你的编译器没有这个)你可以使用这个简单的现在的版本。 (最好把它放在你自己的 namespace 中)

#include <string>
#include <sstream>

std::string to_string(int i){
   std::stringstream s;
   s << i;
   return s.str();
}

关于c++ - 在循环中创建多个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39686185/

相关文章:

c++ - constexpr 函数参数作为模板参数

c++ - std::map 通过变换替换现有元素

c++ - 使用 QTextStream 读取正在写入的文件?

php - 在保持锁定的同时读取和写入文件

perl - 如何判断另一个进程何时停止写入 Perl 中的文件?

html - 上传到服务器后出现问题

C - 给定一个不区分大小写的文件路径,如何检查文件是否存在?

c++ - 交叉编译错误 Visual Studio C++

java - 在 Java 中使用 C++ API

c++ - Cloud Files API 支持哪些 Windows 版本?