Wednesday, October 1, 2014

C++ char array to string

The c style null terminated arrays might be considered a thing of past by many but as a matter fact these things are still there are used in many many large scale legacy software.\

Just recently I observed that a lot of people are trying to find an easy way to make a string out of a character array in C++ so I thought I should write a post and help the poor souls stuck in dark chambers of C++.

Without any further ado, the C++ code to achieve this extremely difficult task is given below.

char array to string c++

using namespace std;
#include<sstream> // must have header fiel

int main(int argc, char* argv[])
 char * charArray = "I love juice";// C style null terminated array or character pointer
 std::ostringstream stringFromCharArray;// object of std::ostringstream which will be used later

 for(int i = 0; 
   i < strlen(charArray); // strlen function is used to determine lenght of a null terminated string
   i++){// for loop to go through the char array
    stringFromCharArray << charArray[i]; // shove the current character into ostringstream

 cout << charArray << endl;// print old c style string
 cout << stringFromCharArray.str() << endl;// print your new fancy c++ style std::string

 // cheerio!!!

 return 0;
}// Do visit my freelance profile

I have tried to put self explanatory comments inside the code but still I will like to elaborate the dcode just to make things easier.
First of all we have char * charArray which is a C style array of characters.
Next we define object std::ostringstream StringFromCharArray which we will use to assemble our string.
In order to make a string out of char * we will traverse the character pointer. I'm using a for loop here, which terminates when all characters inside the string are traversed. You can see strlen function is used here, which is you know ages old method of figuring out length of an array of characters.
Next up I am using stringFromCharArray along with stream read operator, and reading in one character at a time.

By the end of the loop, we will have everything that we need inside our ostringstream object.
Calling the method str of ostringstream object will return us a std::string object which can be used any way we like.

Don't forget to add necessary using statement and header files as well.

using namespace std;
#include<sstream> // must have header fiel


  1. 192.168.l.254.254 is a private IP address that comes under C class IP address. 192.168.l.254 IP address most commonly used private address as the default gateway IP address by many leading router brands.

  2. NAZA We are the service provider Online casinos With every bet A complete answer to the gambler


Feel free to talk back...