如何使用c ++中的for循环将数组放入文件中

问题描述 投票:0回答:1

我声明了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 +']

c++ for-loop concatenation fstream fwrite
1个回答
0
投票

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

您尝试将整数添加到指针,然后将另一个指针添加到结果。那没有道理。

使用std::to_string将整数转换为std::to_string,它应该起作用:

std::string
© www.soinside.com 2019 - 2024. All rights reserved.