Question

Implement a C++ map to store data in a file, such as any .dat or .txt...

Implement a C++ map to store data in a file, such as any .dat or .txt file filled with data. The data should be loaded to map from the data file.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<iostream> //for cout
#include<fstream> //for ifstream
#include<map> //for map
#include<iterator> //for iterator
using namespace std;

//main function
int main()
{
map<int,int> m; //declared variable of map
ifstream in; //declared in stream
in.open("input.txt"); //opens input.txt file
int x,y;
if(in==NULL){ //if file fails to open then prints message and terminates program
cout<<"Error occurred while opening file";
return -1;
}
while(in>>x>>y) //reads values into x and y
{
m.insert(pair<int,int>(x,y)); //inserts values accordingly into map
}
//creates and iterator for map
map<int,int>::iterator it = m.begin();
while(it!=m.end()){ //iterates till end of map and prints the values in map
cout<<it->first<<" "<<it->second<<endl;
it++;
}

return 0; //terminates the program
}

//output screenshot

//input.txt screenshot

//any query, post in the comment section

Add a comment
Know the answer?
Add Answer to:
Implement a C++ map to store data in a file, such as any .dat or .txt...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT