0

I have written the code to read the string values and mapped as key and value. Now I am facing issue in printing the values, if we have given key value as input from unordered map. below is the code. for example if we choose 1 as option that is key is Server and output should be "IN-OLDEB-1" as value.

Data in file as below:

[Server]
IN-OLDEB-1;
[Location]
\\IN-kkkk\PP620DAT;
[ServerAppName]
OPOPAPP;
[DBShareName]
PP620DAT;
[Commits]
10;
[DeTablePath]
\\CDM\DRGdddTBL;

#include "stdafx.h"

#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>

using namespace std;

int main()

{

    ifstream myfile;

    myfile.open("Wconfig.sys");
unordered_map <string, string> database;
    string tag, value;
    if (myfile.is_open())

{
    while (!myfile.eof())
    {

        getline(myfile, tag);
        getline(myfile, value);
        value.pop_back();
        database[tag.substr(1, tag.size() - 2)] = value;
        //database[tag] = value;
        //cout << database["ServerName"] << endl;
    }


string tag_array[] = {
        "Server",
        "Location",
        "ServerAppName",
        "DBShareName",
        "Commits",
        "DeTablePath"};

cout << "Enter your option: " << endl
        << "1 - Server" << endl
        << "2 - Location" << endl
        << "3 - ServerAppName" << endl
        << "4 - DBShareName" << endl
        << "5 - Commits" << endl
        << "6 - DeTablePath" << endl;


int n;
while (cin >> n) 
{
    cout << n << endl;
    if (n >= 1 && n <= 6)
        cout << endl << database[tag_array[n - 1]] <<endl;
    else
        cout << endl << "Enter Valid Input" << endl;
}
return 0;
}
KBS
  • 27
  • 5
  • Since you know every key in the map, printing it by iterating keys is okay. What's the problem you're facing? Or what do you expect to see but you see the unwanted result instead. – Louis Go Aug 03 '21 at 08:32
  • 1
    `while (!myfile.eof())` will only lead to sadness. [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Retired Ninja Aug 03 '21 at 08:34

1 Answers1

0

There are several options:

If unordered_map_name is tha map, and "specific string" is the key that you want to print:

1: cout << unordered_map_name.at("specific string") << endl;

2: cout << unordered_map_name["specific string"] << endl;

3: cout << unordered_map_name.find("specific string")->second << endl;