문제 설명
C++의 파일에서 읽은 값을 사용하는 데 도움이 되나요? (Some help using my values read from a file in C++?)
작성하려는 프로그램에 몇 가지 문제가 있습니다. 누군가 내가 직면한 문제를 처리하는 방법에 대해 약간의 지침을 줄 수 있기를 바랍니다...
여기까지 내 코드는 다음과 같습니다.
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
struct City
{
string name;
int x;
int y;
};
int main()
{
vector<City>Coord;
City entries[10];
ifstream fin("Locations.txt");
int nb_entries;
string name;
int x, y;
for(nb_entries = 0; fin.good() && nb_entries < 10; nb_entries++)
{
fin >> entries[nb_entries].name;
fin >> entries[nb_entries].x;
fin >> entries[nb_entries].y;
cout << "City: " << entries[nb_entries].name << ", ";
cout << "x: " << entries[nb_entries].x << ", ";
cout << "y: " << entries[nb_entries].y << ", " << endl;
}
system("pause");
return 0;
}
텍스트 파일에 저장한 좌표를 읽어 화면에 출력합니다. 텍스트 파일의 형식은 다음과 같습니다.
city1 x1 y1
city2 x2 y2
...
city10 x10 y10
그리고 이 단계의 출력은 내 코드가 작동하는지 확인할 수 있도록 하기 위한 것이었습니다. 이제 내가 해야 할 일은 도시를 선택하는 사용자로부터 입력을 받은 후 이 좌표를 사용하는 것입니다. 좌표를 배열과 벡터로 읽으려고 시도했지만 값으로 저장하고 나중에 프로그램에서 호출하는 가장 좋은 방법을 찾기 위해 고심하고 있습니다. 저는 아직 프로그래밍과 C++에 익숙하지 않으므로 도움을 주시면 감사하겠습니다!
참조 솔루션
방법 1:
One option is to use a map from city names to coordinate pairs like below:
#include <unordered_map>
unordered_map<string, pair<int,int> > myMap;
You can put your data into myMap
like this:
myMap[cityName] = make_pair(x,y);
and can recall them like this:
x = myMap[cityName].first;
y = myMap[cityName].second;