How to use multiple characters as input?

Hey guys, basically I'm working on creating a program for my chem class that will give you the molecular weight of a compound when you put in the name of a compound, like Na2(CO3). I am pretty new to C++ and am only familiar with how to define a character and then cin >> that character, which makes me run into problems with elements like He that have more than one digit. What is the command that allows me to type in more than 1 character and get out a number? Also, do you have any tips for me when I start using the parentheses and coefficents and stuff? I tried something like this, but it didn't work:
char FirstLetter;
float (all elements were here)
char SecondLetter;
cin >> FirstLetter;
cin >> SecondLetter;
if (FirstLetter='H')
{
if (SecondLetter='e')
cout << He;
if (SecondLetter='f')
cout << Hf;
if (SecondLetter='g')
cout << Hg;
if (SecondLetter='o')
cout << Ho;
}

Thanks in advance and any help is appreciated.
Use std::string instead of char, as char is meant to hold only a single character. You can then use std::getline() to read in lines of input at a time into your string.
okay thanks for that info that really helped, but I still have a question. How do I get the function to cout the value of a variable when I type in the variable name (which in this case I want to type in the element symbol, and get back its weight.) Here is what I have right now. Thanks for your help.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
float H=1.008, He=4.003, Li=6.941, Be=9.012, B=10.811, C=12.011, N=14.007, O=15.999, F=18.998, Ne=20.180, Na=22.990, Mg=24.305, Al=26.982, Si=28.086, P=30.974, S=32.065, Cl=35.453, Ar=39.948, K=39.098, Ca=40.078, Sc=44.956, Ti=47.867, V=50.942, Cr=51.996, Mn=54.938, Fe=55.845, Co=58.933, Ni=58.693, Cu=63.546, Zn=65.39, Ga=69.723, Ge=72.64, As=74.922, Se=78.96, Br=79.904, Kr=83.80, Rb=85.468, Sr=87.62, Y=88.906, Zr=91.224, Nb=92.906, Mo=95.94, Ru=101.07, Rh=102.91, Pd=106.42, Ag=107.87, Cd=112.41, In=114.82, Sn=118.71, Sb=121.76, Te=127.60, I=126.90, Xe=131.29, Cs=132.91, Ba=137.33, La=138.91, Ce=140.12, Pr=140.91, Nd=144.24, Sm=150.36, Eu=151.96, Gd=157.25, Tb=158.93, Dy=162.50, Ho=164.93, Er=167.26, Tm=168.93, Yb=173.04, Lu=174.97, Hf=178.49, Ta=180.95, W=183.84, Re=186.21, Os=190.23, Ir=192.22, Pt=195.08, Au=196.97, Hg=200.59, Tl=204.38, Pb=207.2, Bi=208.98, Po=209, At=210, Rn=222, Fr=223, Ra=226, Ac=227, Th=232.04, Pa=231.04, U=238.03;
std::string FirstElement;
std::cout << "Please enter the name of the element.\n";
std::getline(std::cin,FirstElement);
std::cout <<



char g;
cin >> g;
//return 0;
}
So long as you don't have to do any calculations with you numbers, you could do the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

int main()
{
	const int elementAndValue = 2;
	const int totalElements = 3;

	std::string elements[ totalElements ][ elementAndValue ] = { { "H", "1.008" }, { "He", "4.003" }, { "Li", "6.941" } };

	std::string input = "";

	std::cout << "Number: ";
	std::getline( std::cin, input, '\n' );

	for( int i = 0; i < totalElements; ++i )
	{
		if( input == elements[ i ][ 0 ] )
			std::cout << input << " has an atomic mass of: " << elements[ i ][ 1 ] << '\n';
	}

	return 0;
}


If you do need to do calculations, you could just convert them to float later on.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

struct Element {
    string name;
    float weight;
};

string data =
    "H 1.008, He 4.003, Li 6.941, Be 9.012, B 10.811, C 12.011, N 14.007, "
    "O 15.999, F 18.998, Ne 20.180, Na 22.990, Mg 24.305, Al 26.982, Si 28.086, "
    "P 30.974, S 32.065, Cl 35.453, Ar 39.948, K 39.098, Ca 40.078, Sc 44.956, "
    "Ti 47.867, V 50.942, Cr 51.996, Mn 54.938, Fe 55.845, Co 58.933, Ni 58.693, "
    "Cu 63.546, Zn 65.39, Ga 69.723, Ge 72.64, As 74.922, Se 78.96, Br 79.904, "
    "Kr 83.80, Rb 85.468, Sr 87.62, Y 88.906, Zr 91.224, Nb 92.906, Mo 95.94, "
    "Ru 101.07, Rh 102.91, Pd 106.42, Ag 107.87, Cd 112.41, In 114.82, Sn 118.71, "
    "Sb 121.76, Te 127.60, I 126.90, Xe 131.29, Cs 132.91, Ba 137.33, La 138.91, "
    "Ce 140.12, Pr 140.91, Nd 144.24, Sm 150.36, Eu 151.96, Gd 157.25, Tb 158.93, "
    "Dy 162.50, Ho 164.93, Er 167.26, Tm 168.93, Yb 173.04, Lu 174.97, Hf 178.49, "
    "Ta 180.95, W 183.84, Re 186.21, Os 190.23, Ir 192.22, Pt 195.08, Au 196.97, "
    "Hg 200.59, Tl 204.38, Pb 207.2, Bi 208.98, Po 209, At 210, Rn 222, Fr 223, "
    "Ra 226, Ac 227, Th 232.04, Pa 231.04, U 238.03";


int main()
{
    Element elements[200];
    stringstream weights(data);
    string item;
    int count = 0;

    while (getline(weights,item,',')) // comma is the delimiter
    {
        stringstream sitem(item);
        sitem >> elements[count].name >> elements[count].weight;
        count++;
    }

    for (int i=0; i<count; i++)
        cout << i+1 << " " << elements[i].name << "  " << elements[i].weight << endl;

    string FirstElement;
    cout << "Please enter the name of the element.\n";
    cin >> FirstElement;


    int find;
    for (find=0; find<count; find++)
        if (elements[find].name == FirstElement)
            break;

    if (find == count)
        cout << "Element " << FirstElement << " was not found" << endl;
    else
        cout << "Element " << FirstElement
             << " weight = " << elements[find].weight << endl;

    return 0;
}


The first part of the program loads the data into an array. Lines 42 and 43 are simply a debugging aid, to see whether that worked ok.
Last edited on
I understand what you're doing for the most part with the strings, which is no doubt a better way to do it, but the program still isn't working for some reason. Whenever I type in an element/character, the program immediately closes. I have been trying to figure out what is going wrong for an hour now, and I honestly have no idea what to do. Any suggestions? Maybe you can explain a little?
It sounds like you've encountered the "Hello World" problem, where even the simplest and error-free program just closes immediately with no chance to read the output. Please see this post : http://www.cplusplus.com/forum/beginner/1988/

As for the specific code here. Well, your original suggested code used the actual naming of the variables in order to identify each element. The problem with that is the names of the variables exist only before the code is compiled. When the program is actually run, it has been converted to machine language, and the names of the variables don't exist any more.

Therefore a suggested solution is to use an array to hold the list of names and values. My idea was to make the input data as straightforward as possible. It could be read as input from an external disk file, but this data doesn't change very frequently (though the occasional new element is discovered, such as Copernicium). But anyway, it seems reasonable to put the values into the source code, hence the string data at line 12.

At line 31, a stringstream is defined, and loaded with the contents of the data string. A stringstream can be used in a very similar way to an ordinary file.

At line 35, while (getline(weights,item,',')) each item is read from the stream. Here a line of text ends at each comma, thus item will contain "H 1.008" then "He 4.003" and so on.

Next at line 37, another stringstream is created, and loaded with each item in turn. This is a very convenient way to get the name and number. These are read into two separate variables, name and weight. For convenience those two variables are grouped together in a structure called Element (declared at line 7). An array of such Elements is defined at line 30.

So, we get each name and weight and store them together in the array called elements. The size of the array is set to 200 which should be more than adequate (Copernicium has atomic number 112, so 200 is more than generous).

At lines 50 to 53 the array is searched for the name which was input by the user. count contains the actual number of elements in the array. If the item was not found, the loop will step through the entire array, and the variable find will have reached the value count. On the other hand, if a match is found, at line 53, break is executed which exits immediately from the loop, and find retains the value which is the index of the matched item.

Thus at lines 55 to 59, the outcome is displayed.

And at line 62, the return statement ends the program. You may need to insert some code just before the return, to make the program wait for the user to press a key before closing.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.