Re: Safest way to convert char's to int's
From: Alwyn (dt015a1979_at_mac.com.invalid)
Date: 08/16/04
- Previous message: Chris \( Val \): "Re: Lots of design issues needed."
- In reply to: Paul: "Re: Safest way to convert char's to int's"
- Next in thread: Paul: "Re: Safest way to convert char's to int's"
- Reply: Paul: "Re: Safest way to convert char's to int's"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 16 Aug 2004 12:21:47 +0100
In article <5dab091d.0408151914.538502d8@posting.google.com>, Paul
<paulmmm01@hotmail.com> wrote:
> Whatabout sscanf?
More about that in a minute.
> #include <iostream>
>
> int main(){
> /*array of shorts to stick the numbers in and display them*/
> unsigned short* array = new unsigned short[13];
Having allocated an array like this, you should ideally dispose of it.
Of course, in this particular program, it doesn't matter, as the system
will clean up after you when the process exits.
> for(int i=0;i<13;i++){array[i]=0;}
> /*I'm not exactly sure what you meant by hex bytes*/
I believe the OP wanted each dot-separated number in the string to be
stored as a byte in binary form. So your array should be 'unsigned
char', not 'unsigned short'.
I don't see that it is really necessary to set each element to zero the
way you have done; if I was going to do that, I think I'd have used
'memset'.
> char* list = "1.3.6.1.2.1.11.3.2.1.4.25.0";
> unsigned short i=0;
> while(*list!='\0'){
> if(*list=='.'){
> ++array;
> }else{
> sscanf( list, "%d", &i);
Won't work. 'i' will almost certainly contain zero. You need to make
'i' an 'int' for sscanf to work properly.
> *array += i;
Why do an addition? Why not simply assign 'i' to the location?
> if(i>9)++list;
> if(i>99)++list;
Should the list by accident contain a number above 999, your program
will be flummoxed.
> }
> ++list;
> }
> array-=12;
This is only going to work if the data are exactly 13 elements.
> for(int i=0;i<13;i++){
> std::cout<< array[i]<< ' ';
> }
> std::cout<<'\n';
>
> return 0;
> }
>
> Dunno if this is any good but I found it while I was trying to solve
> your problem and thought it was maybe worth mentioning.
Not impressed, sorry. You've broken virtually every rule in the book.
Your program is only useful as an example of how not to do it.
Alwyn
- Previous message: Chris \( Val \): "Re: Lots of design issues needed."
- In reply to: Paul: "Re: Safest way to convert char's to int's"
- Next in thread: Paul: "Re: Safest way to convert char's to int's"
- Reply: Paul: "Re: Safest way to convert char's to int's"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|