【发布时间】:2022-05-11 14:36:34
【问题描述】:
我已经编写了代码来读取字符串值并映射为键和值。现在我在打印值时遇到问题,如果我们将键值作为无序映射的输入。 下面是代码。 例如,如果我们选择 1 作为选项,键是服务器,输出应该是“IN-OLDEB-1”作为值。
文件中的数据如下:
[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;
}
【问题讨论】:
-
由于您知道地图中的每个键,因此通过迭代键打印它是可以的。你面临的问题是什么?或者您希望看到什么,但您却看到了不想要的结果。
-
while (!myfile.eof())只会导致悲伤。 Why is iostream::eof inside a loop condition (i.e.while (!stream.eof())) considered wrong?
标签: c++ c++11 visual-c++