Ok, let's say you wanted to write a program where you weren't sure what order your user would input their arguements.
I'll use an example of a program that accepts an equation with the variable and can solve for the variable. The user should be allowed to input
Code:
5 + x = 3 or
x + 5 = 3 or
25x = 100 or so on...
The idea being, you don't know whether the next value would be a number or a sign or the variable or whatever. To me the obvious answer would be to read the entire thing into a string and parse it. Then it made me think, "What would be the best way to parse a number?" This is the method I came up with.
After you read the input into a string, you go through the string one element at a time. If it's a number, you convert it and add it to an int variable. Then you check the next element. If that's also a number, you multiply your int by 10 then convert the next element and add it. This seemed like the best method to me and I'll explain why later, but first some code to explain this method:
Code:
for (int x = 0; x < string.length(); x++) {
if (atoi(string[x]) <= 9 && atoi(string[x]) >= 0)
i[y] = (i[y] * 10) + atoi(string[x]);
else if (string[x] == " ")
y++;
// ... and whatever else I would do for signs, variables,
// and such...
}
Is there a better way of doing this? Perhaps getline() and using space as the delimeter, then working with that to see if it's a number?