Showing posts with label String Stream. Show all posts
Showing posts with label String Stream. Show all posts

Tuesday, 12 April 2011

isNumeric()

For some reason many C++ programmers believe there is an isNumeric() function available as part of the language. In fact I was searching for the header file to include to get a piece of code to work.

Its not difficult to create a function that will be able to check if the string is numeric or not. Here is the code.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <string>
#include <sstream>

using namespace
std;

bool
isNumeric1(string stringToCheck)
{

bool
numeric = false;

if
(stringToCheck.find_first_not_of("0123456789.") == string::npos)
numeric = true;

return
numeric;
}


bool
isNumeric2(string stringToCheck)
{

bool
numeric = true;
unsigned
i = 0;

while
(numeric && i < stringToCheck.length())
{

switch
(stringToCheck[i])
{

case
'0': case '1': case '2': case '3': case '4': case '5':
case
'6': case '7': case '8': case '9': case '.':
//do nothing
break;
default
:
numeric = false;
}

i++;
}


return
numeric;
}


bool
isNumeric3(string stringToCheck)
{

stringstream streamVal(stringToCheck);
double
tempVal;

streamVal >> tempVal; //If numeric then everything transferred to tempVal

if
(streamVal.get() != EOF)
return
false;
else
return
true;
}


int
main()
{

string str1("123"), str2("134.567"), str3("12AB");
cout << "Approach 1" << endl;
cout << str1 << (isNumeric1(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric1(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric1(str3) ? " is Numeric" : " is Not Numeric") << endl;

cout << "\nApproach 2" << endl;
cout << str1 << (isNumeric2(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric2(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric2(str3) ? " is Numeric" : " is Not Numeric") << endl;

cout << "\nApproach 3" << endl;
cout << str1 << (isNumeric3(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric3(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric3(str3) ? " is Numeric" : " is Not Numeric") << endl;

return
0;
}




Output is as follows:


There are few problems in the program above:

1. It does not cater for negative numbers
2. It will return wrong result when you have incorrect string like 12.34.56.78

I have intentionally left it as an exercise.

Other approaches are possible as well. Why not try and think of an approach yourself.

Tuesday, 8 March 2011

Switch Case using string

When I started thinking of this example, I also faced some of the other problems that I have encountered in my initial days of C++. One of these problems was how to convert String to multiple Ints and how to split strings easily, etc. Hopefully you will find the example useful.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>
#include<sstream>
#include<map>

using namespace
std;

void
split(const string& input, int& num1, int& num2, string& operation);
int
calculate(int num1, int num2, string operation);

int
main()
{

string s[5] = {"2 + 2", "4 - 1", "4 * 6", "18 / 3", "12 ^ 2"};

for
(int i = 0; i < 5 ; i++)
{

int
num1=0, num2=0;
string op;
split(s[i], num1, num2, op);
int
retVal = calculate(num1, num2, op);
cout<<s[i]<<" = "<<retVal<<endl;
}


return
0;
}


void
split(const string& input, int& num1, int& num2, string& operation)
{

istringstream iss(input);
iss >> num1;
iss >> operation;
iss >> num2;
}


int
calculate(int num1, int num2, string operation)
{

enum
Operators {unknown, add, sub, mul, div};
map<string, Operators> mapOfOperators;
mapOfOperators["+"] = add;
mapOfOperators["-"] = sub;
mapOfOperators["*"] = mul;
mapOfOperators["/"] = div;

switch
(mapOfOperators[operation])
{

case
add:
return
num1 + num2;
case
sub:
return
num1 - num2;
case
mul:
return
num1 * num2;
case
div:
return
num1 / num2;
default
:
cout<<"Unrecognised Operator "<<operation<<endl;
}

return
0;
}


The output is as follows:
See Also: Codeguru article on 'Switch on Strings in C++'.

Wednesday, 14 July 2010

Client/Server communication via sockets

The following is a simple Client Server example that actually covers quite a few different topics. The code is modified from the MadWizard.org Winsock Tutorial. It may be a good idea to go through the StringStreams example here and C/C++ String differences example here.

Please note that the code below is not the best example of coding practice.

Server code:



//Original Client-Server code from www.MadWizard.org
//Part of the Winsock networking tutorial by Thomas Bleeker
//Modified and tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

#include <iostream>
#include <string>
#include <sstream>

#define WIN32_MEAN_AND_LEAN
#include <winsock2.h>
#include <windows.h>

//Add ws2_32.lib in Properties->Linker->Input->Additional Dependencies

using namespace
std;

const
int REQ_WINSOCK_VER = 2; // Minimum winsock version required
const int DEFAULT_PORT = 4444;
const
int TEMP_BUFFER_SIZE = 128;

//Forward Declarations
bool RunServer(int portNumber);

//MAIN
int main()
{

int
iRet = 1;
WSADATA wsaData;

cout << "SERVER STARTED" << endl;
cout << "Initializing winsock... ";

if
(WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0), &wsaData)==0)
{

// Check if major version is at least REQ_WINSOCK_VER
if (LOBYTE(wsaData.wVersion) >= REQ_WINSOCK_VER)
{

cout << "initialized.\n";

int
port = DEFAULT_PORT;
iRet = !RunServer(port);
}

else

{

cerr << "required version not supported!";
}


cout << "Cleaning up winsock... ";

// Cleanup winsock
if (WSACleanup()!=0)
{

cerr << "cleanup failed!\n";
iRet = 1;
}

cout << "done.\n";
}

else

{

cerr << "startup failed!\n";
}

return
iRet;
}



string GetHostDescription(const sockaddr_in &sockAddr)
{

ostringstream stream;
stream << inet_ntoa(sockAddr.sin_addr) << ":" << ntohs(sockAddr.sin_port);
return
stream.str();
}


void
SetServerSockAddr(sockaddr_in *pSockAddr, int portNumber)
{

// Set family, port and find IP
pSockAddr->sin_family = AF_INET;
pSockAddr->sin_port = htons(portNumber);
pSockAddr->sin_addr.S_un.S_addr = INADDR_ANY;
}


void
HandleConnection(SOCKET hClientSocket, const sockaddr_in &sockAddr)
{

// Print description (IP:port) of connected client
cout << "Connected with " << GetHostDescription(sockAddr) << ".\n";
exception e;

char
tempBuffer[TEMP_BUFFER_SIZE];

// Read data
while(true)
{

int
retval;
retval = recv(hClientSocket, tempBuffer, sizeof(tempBuffer), 0);
if
(retval==0)
{

break
; // Connection has been closed
}
else if
(retval==SOCKET_ERROR)
{

exception e("socket error while receiving.");
throw
e;
}

else

{

string tempBufferString(tempBuffer);
cout<<"Received over the socket :"<<tempBufferString<<endl;
string tempString = "Loopbacked: " + tempBufferString + '\0';
strcpy_s(tempBuffer, tempString.length() + 1, tempString.c_str());
if
(send(hClientSocket, tempBuffer, strlen(tempBuffer)+1, 0)==SOCKET_ERROR)
{

exception e("socket error while sending.");
throw
e;
}
}
}

cout << "Connection closed.\n";
}


bool
RunServer(int portNumber)
{

SOCKET hSocket = INVALID_SOCKET, hClientSocket = INVALID_SOCKET;
bool
bSuccess = true;
sockaddr_in sockAddr = {0};

try

{

// Create socket
cout << "Creating socket... ";
if
((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{

cout << "failed Creating socket... \n";
return
false;
}

cout << "created.\n";

// Bind socket
cout << "Binding socket... ";
SetServerSockAddr(&sockAddr, portNumber);
if
(bind(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr))!=0)
{

cout << "failed Binding socket... \n";
return
false;
}

cout << "bound.\n";

// Put socket in listening mode
cout << "Putting socket in listening mode... ";
if
(listen(hSocket, SOMAXCONN)!=0)
{

cout << "failed Putting socket in listening mode... \n";
return
false;
}

cout << "done.\n";

// Wait for connection
cout << "Waiting for incoming connection... ";

sockaddr_in clientSockAddr;
int
clientSockSize = sizeof(clientSockAddr);

// Accept connection:
hClientSocket = accept(hSocket,
reinterpret_cast
<sockaddr*>(&clientSockAddr),
&
clientSockSize);

// Check if accept succeeded
if (hClientSocket==INVALID_SOCKET)
{

cout << "accept function failed... \n";
return
false;
}

cout << "accepted.\n";

// Wait for and accept a connection:
HandleConnection(hClientSocket, clientSockAddr);

}

catch
(exception& e)
{

cerr << "\nError: " << e.what() << endl;
bSuccess = false;
}


if
(hSocket!=INVALID_SOCKET)
closesocket(hSocket);

if
(hClientSocket!=INVALID_SOCKET)
closesocket(hClientSocket);

return
bSuccess;
}




Client code:




//Original Client-Server code from www.MadWizard.org
//Part of the Winsock networking tutorial by Thomas Bleeker
//Modified and tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

#include <iostream>
#include <sstream>

#define WIN32_MEAN_AND_LEAN
#include <winsock2.h>
#include <windows.h>

using namespace
std;

//Add ws2_32.lib in Properties->Linker->Input->Additional Dependencies

using namespace
std;

const
int REQ_WINSOCK_VER = 2; // Minimum winsock version required
const char DEF_SERVER_NAME[] = "127.0.0.1"; //localhost - can be your server name like "www.google.com"
const int SERVER_PORT = 4444;
const
int TEMP_BUFFER_SIZE = 128;

// IP number typedef for IPv4
typedef unsigned long IPNumber;

//Forward Declarations
bool RunClient(const char *pServername);

//MAIN
int main(int argc, char* argv[])
{

int
iRet = 1;
WSADATA wsaData;

cout << "CLIENT STARTED" << endl;
cout << "Initializing winsock... ";

if
(WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0), &wsaData)==0)
{

// Check if major version is at least REQ_WINSOCK_VER
if (LOBYTE(wsaData.wVersion) >= REQ_WINSOCK_VER)
{

cout << "initialized.\n";

// Set default hostname:
const char *pHostname = DEF_SERVER_NAME;
iRet = !RunClient(pHostname);
}

else

{

cerr << "required version not supported!";
}


cout << "Cleaning up winsock... ";

// Cleanup winsock
if (WSACleanup()!=0)
{

cerr << "cleanup failed!\n";
iRet = 1;
}

cout << "done.\n";
}

else

{

cerr << "startup failed!\n";
}

return
iRet;
}



IPNumber FindHostIP(const char *pServerName)
{

HOSTENT *pHostent;

// Get hostent structure for hostname:
if (!(pHostent = gethostbyname(pServerName)))
{

exception e("could not resolve hostname.");
throw
e;
}


// Extract primary IP address from hostent structure:
if (pHostent->h_addr_list && pHostent->h_addr_list[0])
return
*reinterpret_cast<IPNumber*>(pHostent->h_addr_list[0]);

return
0;
}


void
FillSockAddr(sockaddr_in *pSockAddr, const char *pServerName, int portNumber)
{

// Set family, port and find IP
pSockAddr->sin_family = AF_INET;
pSockAddr->sin_port = htons(portNumber);
pSockAddr->sin_addr.S_un.S_addr = FindHostIP(pServerName);
}


bool
RunClient(const char *pServername)
{

SOCKET hSocket = INVALID_SOCKET;
char
tempBuffer[TEMP_BUFFER_SIZE];
sockaddr_in sockAddr = {0};
bool
bSuccess = true;

try

{

// Lookup hostname and fill sockaddr_in structure:
cout << "Looking up hostname " << pServername << "... ";
FillSockAddr(&sockAddr, pServername, SERVER_PORT);
cout << "found.\n";

// Create socket
cout << "Creating socket... ";
if
((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{

cout<<"could not create socket. "<<endl;
return
false;
}

cout << "created.\n";

// Connect to server
cout << "Attempting to connect to " << inet_ntoa(sockAddr.sin_addr)
<<
":" << SERVER_PORT << "... ";
if
(connect(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr))!=0)
{

cout<<"could not connect. "<<endl;
return
false;
}

cout << "connected.\n";

cout << "Sending requests and checking for loopbacks... "<<endl;

//Lets sent 100 packets and get it looped back from Server
for(int i = 0; i < 10; i++)
{

int
retval = 0;
stringstream ss (stringstream::in | stringstream::out);
ss << "Message " << i <<"\n";

std::string s = ss.str() + '\0'; //Adding the null charachter
if (send(hSocket, s.c_str(), s.size() + 1, 0)==SOCKET_ERROR)
{

cout<<"failed to send data. "<<endl;
return
false;
}


retval = recv(hSocket, tempBuffer, sizeof(tempBuffer), 0);
if
(retval==0)
{

cout<<"Connection closed"<<endl;
break
;
}

else if
(retval==SOCKET_ERROR)
{

exception e("socket error while receiving.");
throw
e;
}

else

{

// retval is number of bytes read
// Terminate buffer with zero and print as string
tempBuffer[retval] = 0;
cout << "Received " << retval << " bytes. Received : " <<tempBuffer;
}
}
}

catch
(exception& e)
{

cerr << "\nError: " << e.what() << endl;
bSuccess = false;
}


if
(hSocket!=INVALID_SOCKET)
{

closesocket(hSocket);
}

return
bSuccess;
}





The Server Output is as follows:


The Client output is as follows:

Wednesday, 30 June 2010

Example of Permutations in C++

Example of how you can let the Algorithm class generate permutations of String



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>

using namespace
std;

int
main()
{

string someString="ABC";
vector<string> someVector;

someVector.push_back(someString);

string::iterator itBegin = someString.begin();
string::iterator itEnd = someString.end();

while
(next_permutation(itBegin, itEnd)) //std::next_permutation defined in algorithm
{
someVector.push_back(string(itBegin, itEnd));
}

copy(someVector.begin(), someVector.end(), ostream_iterator<string>(cout, "\n"));

return
0;
}



The output is as follows:


Wednesday, 17 March 2010

Example of Stringstreams

Here is an example of stringstream that I picked up from here and modified it slightly.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of C++ stringstreams

#include<iostream>
#include<sstream>
#include<string>

using namespace
std;

int
main()
{

string input;

cout<< "Please enter some numbers speretaed by space and press enter once done: ";
getline(cin, input);

cout<< "input = " << input << endl;

stringstream memString(input, ios_base::in); //stringstream( string s, openmode mode )

cout<<"memString = " << memString << endl;
cout<<"memString (contents) = " << memString.str() << endl;

double
summ = 0;
double
temp;
while
(memString >> temp)
{

summ+= temp;
}


cout<<"summ = " << summ << endl;

return
0;
}








The output is as follows:


See Also:
C++ Reference on stringstreams
Using Stringstreams in C++
String Stream example
String Streams Constructors