Showing posts with label String. Show all posts
Showing posts with label String. 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, 5 April 2011

string::find_next()

I met this new starter who has come from Java background. He was upset because he couldn't find string::find_next() as C++ function. He said Java is much more flexible this way. In reality, its not that bad if you look at the definition of find carefully.

size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

The first one works as find_next as I show in the example below:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

#include <iostream>
#include <string>

using namespace
std;

int
main()
{

string someString("Tom is not in. Infact Tom is not going to be in Tomorrow or day after Tomorrow");
string findTheString("Tom");

unsigned
position = 0;

position = someString.find(findTheString);
cout<<"First position of " << findTheString << " is " << position << endl;

//We want to find all the next positions which is after position + findTheString.length()
while(position != string::npos)
{

position = someString.find(findTheString, (position + findTheString.length()));
cout<<"Next position of " << findTheString << " is " << position << endl;
}


return
0;
}



The output is as follows:

Exercise for new programmers:
  1. The last two Tom's are part of 'Tomorrow', how can you make sure they are not printed
  2. The last Tom which is 4294... is equal to -1 or string::npos. How can you stop that being printed without making another check for string::npos
Please dont post answers as they should be trivial exercise and you should be able to figure out without much problems.

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++'.

Friday, 4 March 2011

Removing all white-spaces from a string

Continuing on the same theme as the last post. What if all the spaces need to be stripped out from the input string:



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

using namespace
std;

string removeAllSpaces(const string& s)
{

string newStr(s);
bool
spacesLeft = true;

while
(spacesLeft)
{

int
pos = newStr.find(" ");
if
(pos != string::npos)
{

newStr.erase(pos, 1);
}

else

spacesLeft = false;
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeAllSpaces(aString)<<endl;

return
0;
}





The output is as follows:

Tuesday, 1 March 2011

Removing Multiple White-spaces from a string

A simple program to remove an arbitrary number of white spaces in between words. Program as follows:




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

using namespace
std;

bool
removeDoubleSpaces(string& s)
{

bool
found = true;

int
i = s.find(" "); //Search for 2 spaces
if(i != string::npos)
{

s.replace(i, 2, " ");
}

else

found = false;

return
found;
}


string removeMultipleSpaces(const string& s)
{

string newStr(s);
bool
found = true;

while
(found)
{

found = removeDoubleSpaces(newStr);
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeMultipleSpaces(aString)<<endl;

return
0;
}




The output is as follows:

Wednesday, 25 August 2010

An example of replacing part of strings

Taking a bit of break from the Design Patterns this week. We look at a simple example of replacing part of the strings. For example you may have a program which prints out some customised letter. You may want to replace the default name with the name of a person that can be input on command line.



Example as follows:





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

using namespace
std;

int
main()
{

string s1 = "Hello is that Tom? Are you ok Tom? Take Care tom!";
string s2 = "Tom";
string s3 = "William";

cout << "s1 = " << s1 << endl;

//Find s2 and replace by s3
bool flag = true;
while
(flag)
{

size_t found = s1.find(s2);
if
(found != string::npos)
{

s1.replace(found, s2.length(), s3);
}

else

{

flag = false;
}
}


cout << "s1 = " << s1 << endl;

return
0;
}






The output is as follows:







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, 26 May 2010

std::search example on vector and string

Continuing from last weeks theme, here is a simple example of std::search.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> //needed for std::search

using namespace
std;

bool
isOdd(int i)
{

return
((i%2)==1);
}


int
main()
{

vector<int> v1;
v1.push_back(88);
v1.push_back(99);
v1.push_back(22);
v1.push_back(33);
v1.push_back(44);
v1.push_back(55);
v1.push_back(66);
v1.push_back(77);

//Demonstrating Search - Matching Case
vector<int> v2;
v2.push_back(22);
v2.push_back(33);
v2.push_back(44);

vector<int>::const_iterator it = search(v1.begin(), v1.end(), v2.begin(), v2.end());
if
(it != v1.end())
{

cout<<"Found: "<<*it<<endl;
cout<<"Position = "<<it - v1.begin() + 1<<endl;
}

else

{

cout<<"Not Found"<<endl;
cout<<"Position = -1"<<endl;
}


//Demonstrating Search - Non-Matching Case
vector<int> v3;
v3.push_back(22);
v3.push_back(33);
v3.push_back(444); //non matching

it = search(v1.begin(), v1.end(), v3.begin(), v3.end());
if
(it != v1.end())
{

cout<<"Found: "<<*it<<endl;
cout<<"Position = "<<it - v1.begin() + 1<<endl;
}

else

{

cout<<"Not Found"<<endl;
cout<<"Position = -1"<<endl;
}


//Use the search to find strings
string s1="Hello, this is Zahid";

//Matching case
string s2="Zahid";

string::const_iterator it2 = search(s1.begin(), s1.end(), s2.begin(), s2.end());
if
(it2 != s1.end())
{

cout<<"Found: "<<*it2<<endl;
cout<<"Position = "<<it2 - s1.begin() + 1<<endl;
}

else

{

cout<<"Not Found"<<endl;
cout<<"Position = -1"<<endl;
}


//Non-Matching case
string s3="None";

it2 = search(s1.begin(), s1.end(), s3.begin(), s3.end());
if
(it2 != s1.end())
{

cout<<"Found: "<<*it2<<endl;
cout<<"Position = "<<it2 - s1.begin() + 1<<endl;
}

else

{

cout<<"Not Found"<<endl;
cout<<"Position = -1"<<endl;
}


return
0;
}






The output is as follows:

Wednesday, 24 March 2010

Case-Insensitive String comparison

It is often a problem that we ask someone to input some string for comparison but they often put different case and the comparison fails. For example if we are expecting a string, say, 'true'. The user may input 'True' or 'TRUE'. A simple comparison will fail in this case.

The following is a simple program to convert the input string to lower case. What this would allow is to do a case-insensitive search.



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

using namespace
std;

//First approach for converting into lower case
string toLowerString(string& input)
{

int
length = input.length();
string output;
for
(int i = 0; i < length; i++)
{

output += tolower(input[i]);
}

return
output;
}


//Second approach for converting into lower case
string toLowerString(string& input, bool approach2) //Overloaded method
{
int
length = input.length();
string output;
for
(int i = 0; i < length; i++)
{

if
(input[i] >= 0x41 && input[i] <= 0x5A) //Ascii for A-Z
output += (input[i] + 0x20); //ascii for a-z
else
output += input[i];
}

return
output;
}


int
main()
{

string s1="true";
string s2("TRUE");
string s3;
s3 = "True";

//Check if s1 = s2
if(s1 == s2)
cout<<"s1 == s2"<<endl;
else

cout<<"s1 != s2"<<endl;

//Check if s1 = s2 with first approach
if(s1 == toLowerString(s2))
cout<<"s1 == Approach1::toLowerString(s2)"<<endl;
else

cout<<"s1 != Approach1::toLowerString(s2)"<<endl;

//Check if s1 = s2 with second approach
if(s1 == toLowerString(s2,true))
cout<<"s1 == Approach2::toLowerString(s2)"<<endl;
else

cout<<"s1 != Approach2::toLowerString(s2)"<<endl;


//Check if s1 = s3 with second approach
if(s1 == s3)
cout<<"s1 == s3"<<endl;
else

cout<<"s1 != s3"<<endl;

if
(s1 == toLowerString(s3,true))
cout<<"s1 == Approach2::toLowerString(s3)"<<endl;
else

cout<<"s1 != Approach2::toLowerString(s3)"<<endl;

//Check if s1 = s3 with second approach
if(s1 == toLowerString(s3))
cout<<"s1 == Approach1::toLowerString(s3)"<<endl;
else

cout<<"s1 != Approach1::toLowerString(s3)"<<endl;

return
0;
}





The output is as follows:


I am aure much better approaches are possible. If you have a better example please share.

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

Monday, 16 November 2009

C String and C++ Strings: Similarities and Differences

I came across this scenario recently when a C style string (as some people refer to char[] as) had to be compared to a C++ string and even though this is straightforward, i fell in the same trap as a lot of people about forgetting that there is a Nul charachter as the end of C style string. Anyway, here is an example to demonstrate both the strings.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate length and size of char* and string
//and to show similarity and difference between them
#include<iostream>

using namespace
std;

int
main()
{

cout<<endl;
char
a[10]="Hello";
cout<<"Size of a = "<<sizeof(a)<<endl;
a[5]='\0'; //Terminating the C string in between with Nul character
cout<<"Size of a = "<<sizeof(a)<<endl;

cout<<endl;
char
b[]="Hello";
cout<<"Size of b = "<<sizeof(b)<<endl; //Note the size
//Automatic Nul charachter added

cout<<endl;
string c("Hello");
cout<<"Size of c = "<<sizeof(c)<<endl;
cout<<"Length of c = "<<c.length()<<endl;

c += " Zahid";
cout<<"Size of modified c = "<<sizeof(c)<<endl;
cout<<"Length of modified c = "<<c.length()<<endl;

//Add an extra NULL charachter
cout<<endl;
char
d[]="Hello\0";
cout<<"Size of d = "<<sizeof(d)<<endl;
for
(int i = 0; i < sizeof(d); i++)
{

cout<<"d["<<i<<"] = "<<d[i]<<endl;
}


//When is a char[] similar to string?
cout<<endl;
char
e[]="Zahid";
string f = "Zahid\0";
const
char* temp = f.c_str();
if
(strcmp(e , temp) == 0)
{

cout<<"e == f"<<endl;
}

else

{

cout<<"e != f"<<endl;
}


return
0;
}







The output is as follows: