Click here to Skip to main content
15,885,917 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
For example:
CString ip_address = _T("192.168.0.213");

I want to know the method to move each int value 192,168,0,213 to each of char variable with size 1.

Like this:


char ipaddr[4];

ipaddr[0] = 192;

ipaddr[1] = 168;

ipaddr[1] = 0;

ipaddr[1] = 213;

Yes, What I really know is the method of the datatype conversion CString(or char string) to
integer variables.

Thank you.

What I have tried:

In this evening, 3-4 more hours wasted for this problem.
Posted
Updated 26-Apr-16 3:03am

This has been asked and answered multiple times. It is just a question of finding the correct search term. I used "c++ parse ip string" and got a lot of useful results:
C++ how to convert ip address to bytes? - Stack Overflow[^]
c - parsing ip adress string in 4 single bytes - Stack Overflow[^]

Once you have choosen a parsing method you must observe that your string is CString (TCHAR *). Therefore, use the _t* versions of the C standard library (e.g. _stscanf). Because most string to integer conversions return an integer, you must cast them to bytes when assigning.

Example using sscanf / _stscanf:
C++
unsigned short a, b, c, d;
// May check the return value here (should be 4) for basic validity check
_stscanf(ip_address.GetString(), _T("%hu.%hu.%hu.%hu"), &a, &b, &c, &d);
unsigned char ipaddr[4];
ipaddr[0] = static_cast<unsigned char>(a);
ipaddr[1] = static_cast<unsigned char>(b);
ipaddr[2] = static_cast<unsigned char>(c);
ipaddr[3] = static_cast<unsigned char>(d);
 
Share this answer
 
There are several ways to accomplish such a task. You can, for instance, use the Tokenize[^] method to extract all (the string representations of) the octects ant then convert each string to the corresponding byte (e.g. using itoa[^]).
 
Share this answer
 
Split the string at each comma, and use the datatype conversion you already know about on each part. Then just cast the integer value to a byte (or unsigned char) and assign to the four elements to your ipaddr array.
But don't declare it as char - that's a signed 7 bit quantity and IP address elements are unsigned 8 bit values and should be treated as such.
[edit]Minor typos[/edit]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900