【问题标题】:Writing results to multiple txt files in C++在 C++ 中将结果写入多个 txt 文件
【发布时间】:2021-11-26 14:34:05
【问题描述】:

我有以下代码:

#include <fstream>
#include <iostream>

using namespace std;


int main() {
  ofstream os;
  char fileName[] = "0.txt";
  for(int i = '1'; i <= '5'; i++)
  {
     fileName[0] = i;
     os.open(fileName);
     os << "Hello" << "\n";
     os.close();
  }
  return 0;
}

目的是将我的代码输出写入多个 .txt 文件,最多 64 次。当我将此循环更改为运行超过 10 次时,即

for(int i = '1'; i <= '10'; i++)

我收到以下错误:

警告:字符常量对于它的类型来说太长了

任何想法如何写入超过 10 个文件?此外,如何在每个“Hello”之后写一个数字,例如“Hello1 ... Hello10”?

干杯。

【问题讨论】:

    标签: c++ save fstream txt


    【解决方案1】:

    我相信您收到该警告的原因是因为您试图将两个字符分配到 char 数组的一个槽中:

    fileName[0] = i;
    

    因为i = 10;时不再是单个字符了。

    #include <fstream>
    #include <iostream>
    #include <string>//I included string so that we can use std::to_string
    
    using namespace std;
    
    
    int main() {
        ofstream os;
        string filename;//instead of using a char array, we'll use a string
        for (int i = 1; i <= 10; i++)
        {
            filename = to_string(i) + ".txt";//now, for each i value, we can represent a unique filename
            os.open(filename);
            os << "Hello" << std::to_string(i) << "\n";//as for writing a number that differs in each file, we can simply convert i to a string
            os.close();
        }
        return 0;
    }
    

    希望这以您满意的方式解决了问题;如果您需要任何进一步的说明,请告诉我! (:

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2016-06-08
      • 1970-01-01
      • 2015-09-20
      • 2021-10-23
      • 2016-03-02
      • 2016-01-08
      • 1970-01-01
      • 2011-11-30
      相关资源
      最近更新 更多