【问题标题】:How to put array into file using for loop in c++如何在 C++ 中使用 for 循环将数组放入文件
【发布时间】:2023-08-28 09:58:01
【问题描述】:

我已经声明了 3 个数组,其中 parent 数组中的每个元素都是父级的名称,dollahmamat 数组由它们的子级的名称组成。

ofstream WFile;
string parent[]={"dollah","mamat"};
string dollah[]={"aniza","azman","azilawati"};
string mamat[]={"mad","rushdi","roslan"};

我想做一个FOR loop,可以用来把孩子们的名字放在他们自己的family文件中。

for (int i=0; i<14;i++){
    len= cout<<(sizeof(parent[i))/cout<<sizeof((parent[i])[0]);

    WFile.open("Family"+i+".txt");
    if(WFile.is_open()){
    cout<<"File opened"<<endl;
    for(int j=0;j<len;j++){
        WFile<<(parent[i])[j]<<endl;    
        }
    }else{
        cout<<"File cannot opened"<<endl;
    }
    WFile.close();
}

错误显示

[错误] 'const char*' 和 'const char [5]' 类型的无效操作数转换为二进制 'operator+'

【问题讨论】:

  • 为什么要按照你的方式计算字符串的长度?为什么不直接使用parent[i].length()?更不用说您所做的计算甚至都不起作用,因为 std::string 对象的大小不等于字符串的长度。
  • 我应该如何解决这个问题,因为目前,文件只写了父母的名字。不是孩子的名字。
  • 你所做的计算实际上比我最初看到的要糟糕。你所做的本质上是len = cout / cout;。更不用说您显示的代码中有语法错误。创建minimal reproducible example 向我们展示时,请确保它复制了您所询问的问题,仅此而已。然后将其按原样复制粘贴到问题中,不要重写它。

标签: c++ for-loop concatenation fstream fwrite


【解决方案1】:

文字字符串实际上是常量字符数组,因此会衰减为指针(即char const*)。

您尝试将整数添加到指针,然后将另一个指针添加到结果。这没有任何意义。

使用std::to_string 将整数转换为std::string,它应该可以工作:

"Family"+std::to_string(i)+".txt"

【讨论】: