Separating char input

Greetings,

I'm still in the process of learning rather basic C++. I am trying to code a program that performs equations with chemical formulas. I am using char as input. The problem that I have hit is this: I need a way to separate what is in the input. For example: if a user inputs CO2, then I need a way to separate C from O and also a way to multiply O by 2. Does anyone have ideas that could help me here? Thanks,
An elementary parser... we've had a problem like this before.

Create a string array or char * array. Every time you find a capital letter, advance to the next element of your array, and continue reading. Be sure to remember the number of characters read before the next capital letter OR DIGIT.

If you find a digit, read until you get another capital letter, copy the characters between the two letters into a small temp string, then use atoi(string.c_str()) to get your number. Then, copy the last set of characters that you read that many - 1 times into your array.

This will help:
http://cplusplus.com/reference/clibrary/cctype/

-Albatross
Last edited on
Yes! That is exactly what I need! Thanks a million.
For parsing peek() is your friend:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

std::string parse_element(std::istream& is)
{
	std::string elem;
	if(is && std::isupper(is.peek()))
	{
		elem.append(1, is.get());
		while(is && std::islower(is.peek()))
		{
			elem.append(1, is.get());
		}

		// etc...
	}
	return elem;
}



Or something similar.
Actually this is a much safer way to read in characters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::string parse_chem(std::istream& is)
{
	std::string elem;

	char ch;
	if(std::isupper(is.peek()) && is >> ch) // if will only succeed if the read is >> ch was successful 
	{
		elem.append(1, ch); // so you know you have a valid char here
		while(std::islower(is.peek()) && is >> ch)
		{
			elem.append(1, ch); // and here
		}
	}

	// the length of elem will be 0 on failure; elem.length() > 0 implies success
	return elem;
}
Topic archived. No new replies allowed.