Reputation:
I'm working on a stoichiometry calculator in C++. I've stored the properties of each element into data structures. Each data structure is named after the element's symbol. What I want is for the user to be able to type in the symbol of an element and have the program output/use the values in the structure. Example:
User input: He
Program Output: Helium 1 1.00794
How can I do this?
Upvotes: 0
Views: 94
Reputation: 24118
Store data structures in a std::map with symbol as the key. On user input, use std::map::find() to find the symbol in the map and print data in the found data structure
#include <iostream>
#include <map>
struct element
{
std::string symbol;
std::string name;
double stoichiometry;
};
int main()
{
element hydrogen;
hydrogen.symbol = "H";
hydrogen.name = "Hydrogen";
hydrogen.stoichiometry = 2;
element helium;
helium.symbol = "He";
helium.name = "Helium";
helium.stoichiometry = 1.5;
std::map<std::string, element> elements;
elements[hydrogen.symbol] = hydrogen;
elements[helium.symbol] = helium;
std::string symbol;
std::cout << "Enter element symbol: ";
std::cin >> symbol;
std::map<std::string, element>::iterator it(elements.find(symbol));
if (it != elements.end())
{
std::cout << it->second.name << " " << it->second.stoichiometry << std::endl;
}
else
{
std::cout << "Symbol " << symbol << " not found";
}
return 0;
}
Upvotes: 2