Solved

# Parsing string

Posted on 2006-04-20
261 Views
I need to parse a string of integers like this:

string line = "123456..etc";
int result;

I need every single digit converted to a number so I am doing something like this:

for (int i = 0; i < line.length(); i++)
{
result = atoi(&line[i]);
}

Instead of breaking the string up I get:

123456
23456
3456, Etc.

What is the best way to do this.  Thank you very much ahead of time.

Nick
0
Question by:nstefanov

LVL 86

Expert Comment

The easiest way would be to

for (int i = 0; i < line.length(); i++)
{
result = line[i] - '0';
}
0

LVL 49

Accepted Solution

int main ()
{
string line = "123456..etc";
string sOneDigit = "";
int result;

for (int i = 0; i < line.length(); i++) {
sOneDigit= line[i];                 // a one-character string
result = atoi( sOneDigit.c_str() );
cout << result << endl;
}
return 0;
}

This version lets you continue to use atoi()... but it breaks out each digit of the original line into a separate string.  That lets you avoid using the "little secret" that the ASCII value of digits '0' - '9' equate to a corresponding binary value when you subtract exactly 0x30 ('0').  I understand that in a future version of the the ANSI STL spec, the digits are not guaranteed to be in any particular order (just kidding).
0

LVL 86

Expert Comment

?
0

Author Comment

jkr your method also works great i just thought Dan's is a little more complete.  Maybe should have split the points.  Will have to find out how to do that.  Thanks for your help.

Nick
0

LVL 86

Expert Comment

>>i just thought Dan's is a little more complete

To what extent? You wanted to convert chars into ints, not chars into strings that you then convert to ints.
0

Author Comment

I meant explanation.  Thanks again.

Nick
0

## Featured Post

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.