Storing some values from a string to some chars
Sep 28, 2010 at 12:19pm UTC
1 2 3 4 5 6 7 8
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
unsigned char content[20] = "ip1=10&ip2=10&ip3=4&ip4=210" ;
unsigned char ip_addr[4] = { 0,0,0,0};
Hello all,
I want the value from my content array after the = and before the & for each of the 4 ip numbers stored in ip_addr[4]. The problem is, the numbers are variable in length.
Last edited on Sep 28, 2010 at 12:20pm UTC
Sep 28, 2010 at 12:25pm UTC
hello jimclermonts,
use
strchr()
to find '=' and '&' then you can isolate the number (and convert it is necessary)
The example how to use strchr
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/* STRCHR.C: This program illustrates searching for a character
* with strchr (search forward).
*/
#include <string.h>
#include <stdio.h>
int ch = 'r' ;
char string[] = "The quick brown dog jumps over the lazy fox" ;
char fmt1[] = " 1 2 3 4 5" ;
char fmt2[] = "12345678901234567890123456789012345678901234567890" ;
void main( void )
{
char *pdest;
int result;
printf( "String to be searched: \n\t\t%s\n" , string );
printf( "\t\t%s\n\t\t%s\n\n" , fmt1, fmt2 );
printf( "Search char:\t%c\n" , ch );
/* Search forward. */
pdest = strchr( string, ch );
result = pdest - string + 1;
if ( pdest != NULL )
printf( "Result:\tfirst %c found at position %d\n\n" ,
ch, result );
else
printf( "Result:\t%c not found\n" );
/* Search backward. */
pdest = strrchr( string, ch );
result = pdest - string + 1;
if ( pdest != NULL )
printf( "Result:\tlast %c found at position %d\n\n" , ch, result );
else
printf( "Result:\t%c not found\n" );
}
Sep 28, 2010 at 2:13pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
int main()
{
unsigned char content[] = "ip1=10&ip2=10&ip3=4&ip4=210" ;
unsigned char ip_addr[4] = { 0,0,0,0};
stringstream ssip;
string sc = (const char *)content;
string::size_type fpos1 = sc.find('=' ), fpos2;
while (fpos1 != string::npos){
fpos2 = sc.find('&' , fpos1);
if (fpos2 != string::npos)
ssip << sc.substr(fpos1 + 1, fpos2 - fpos1 - 1) << " " ;
else
ssip << sc.substr(fpos1 + 1);
fpos1 = sc.find('=' , fpos2);
}
size_t i = 0;
int ip;
while (ssip >> ip)
ip_addr[i++] = ip;
//Display ip_addr array
copy(ip_addr, ip_addr+4, ostream_iterator<int >(cout, ":" ));
}
Sep 30, 2010 at 2:16pm UTC
Thanks guys for the quick reply, will post the completed code tomorrow :)
Topic archived. No new replies allowed.