Why is Multimap not writing all values at one index to a text file?

Viewed 48

I am simply trying to write data from multimap to a text file in C++. My multimap contains two values at one key, although it outputs both values on the console, but it writes the key and value of the first one only in the file (means it writes only "a" and "100"). Why isn't it writing both values to File? This is my code


int main() {

    multimap<string, string> rec;
    rec.insert({"a", "100"});
    rec.insert({"a", "200"});
    writeFile("a", rec);

}


void writeFile(string a, multimap<string, string> rec) {
    ofstream data;

    for (auto i = rec.find("a"); i != rec.end(); i++) {

data.open("file4.txt");

data << i->first << '\t' << i->second << '\n';

    }

}
1 Answers

The problem is that you have put data.open("file4.txt"); inside the for loop and so it overwrite the old value with the new one. To solve this bring it outside the loop.

void writeFile(string a, multimap<string, string> rec) {
//----------------vvvvvvvvvvv------>use here outside for loop
    ofstream data("file4.txt");
    
    for (auto i = rec.find("a"); i != rec.end(); i++) 
    {
        data << i->first << '\t' << i->second << '\n';

    }
    
}

Working demo

Or

void writeFile(string a, multimap<string, string> rec) {
    ofstream data;
    
    data.open("file4.txt"); //this is now outside for loop
    for (auto i = rec.find("a"); i != rec.end(); i++) 
    {
        data << i->first << '\t' << i->second << '\n';

    }
    
}
Related