While I am running the code, the File(.csv) transfer the data into the map but the first line prints as the last line in Map. Even I am able to find only the last key in the file skipping all other keys in the Map.
Data in my file:- (file.csv)
9956,Aus
9955,Aus
A03A1,Bzl
A03B1,Bzl
I have tried the same code for Windows Environment and the code is running fine. Need to execute the same in Ubuntu Environment.
#include <fstream>
#include <map>
#include <utility>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
ifstream myfile;
myfile.open("file.csv");
std::multimap<std::string, std::string> myMap;
string key;
string value;
if(myfile)
{//file opened
while (!myfile.eof())
{
getline(myfile,key,',');
myfile>>value; //read the next value from the file
key.erase(std::remove(key.begin(), key.end(), '\n'), key.end());
myMap.insert(pair <string, string> (key, value));
}
}
multimap<string, string>::iterator it;
for(it=myMap.begin();it!=myMap.end(); ++it)
cout<<it->first<<"=>"<<it->second<<endl; //display the key/value pair
string input;
cout << "Enter the code: ";
cin >> input;
it = myMap.find(input); //user input stored in it
if (it != myMap.end()) //compare the input with the keys
{
cout << " The code belongs to = " << it->second << endl;
}
else
{
cout << "The code is not available " << endl;
}
myfile.close();
return 0;
}
Actual Output:-
9955=>Aus
A03A1=>Bzl
A03B1=>Bzl
9956=>Aus
Enter the code: A03A1
The code is not available.
Expected Output:-
9956=>Aus
9955=>Aus
A03A1=>Bzl
A03B1=>Bzl
Enter the code: A03A1
The code is belongs to Bzl