Afficher un message
Vieux 06/02/2008, 02h18   #6
Daniel T.
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Converting a substring to Integer

sparkydarky <markdueck.bz@gmail.com> wrote:

> I have a bunch of strings in a database that have in them a number I
> want to extract. Here's the example code I've been working with:
>
> AnsiString tmp = "AMjsdfdsdfj 457756 some description";


What is an "AnsiString"?

> int firstDelim = 0;
> int secondDelim = 0;
>
> for(int i=0; i<=tmp.Length(); i++)
> {


What exactly does "IsDelimiter" do?

> if(IsDelimiter(" ", tmp, i));
> {
> if ( firstDelim == 0 )
> firstDelim = i;
> else
> {
> secondDelim = i;
> break;
> }
> }
> if ( secondDelim > 0 )
> break;
> }
> int str_length = secondDelim - firstDelim;
> ShowMessage(tmp.SubString(firstDelim, str_length));
>
> Can someone give me a hint how to get this to work?


I'm not entirely sure what you think the above should do in the first
place. You leave a lot to be assumed... My assumptions: the various
parts of the string are separated by at least one space character, that
AnsiString can be inserted into a stringstream, and that you only want
to extract the first number in the string... There might be some other
assumptions I didn't think of.

int extractNumber( const string& str )
{
int result = 0;
stringstream ss( str );
while ( !( ss >> result ) ) {
if ( !ss.eof() ) {
ss.clear();
ss.ignore( numeric_limits<streamsize>::max(), ' ' );
}
else {
throw runtime_error( "no number" );
}
}
return result;
}

What the code does. Put the string into a stringstream, then attempt to
extract a number from it. For as long as we can't extract a number: if
we aren't at the end of the stream, clear the stream, scan to the next
space, and try again. Otherwise, throw an error indicating that no
number was found.
  Réponse avec citation
 
Page generated in 0,05024 seconds with 9 queries