Search code examples
c++for-loopconcatenationfstreamfwrite

How to put array into file using for loop in c++


I have declared 3 arrays where each element in parent array is the name of the parent, and dollah and mamat array consist of name of their children.

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

I want to make a FOR loop that can be used to put the name of the children in their own family file.

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();
}

The error shows

[Error] invalid operands of types 'const char*' and 'const char [5]' to binary 'operator+'


Solution

  • Literal strings are really arrays of constant characters, and as such will decay to pointers (i.e. char const*).

    You try to add an integer to a pointer, and then add another pointer to the result. That makes no sense.

    Use std::to_string to convert the integer to a std::string and it should work:

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