首页 > 解决方案 > 代码在 Windows 上运行良好,但在 Linux 平台上使用它时出现问题

问题描述

当我运行代码时,文件(.csv)将数据传输到地图中,但第一行打印为地图中的最后一行。即使我只能找到文件中的最后一个键,跳过地图中的所有其他键。

我文件中的数据:- (file.csv)

9956,Aus
9955,Aus
A03A1,Bzl
A03B1,Bzl

我已经为 Windows 环境尝试了相同的代码,并且代码运行良好。需要在 Ubuntu 环境中执行相同的操作。

    #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;
     }

实际输出:-

     9955=>Aus
     A03A1=>Bzl
     A03B1=>Bzl
     9956=>Aus
      Enter the code: A03A1
      The code is not available.

预期输出:-

      9956=>Aus
      9955=>Aus
      A03A1=>Bzl
      A03B1=>Bzl
      Enter the code: A03A1
      The code is belongs to Bzl

标签: c++dictionary

解决方案


推荐阅读