Jul 13, 2010 at 2:01pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cstring>
using namespace std;
string convert(char kter[],int len)
{
char *kar = new char [len];
for (int i=0;i<len;i++) kar[i] = kter[i];
string newstr = kar;
return newstr;
}
int main(){
int n=100;
char ch[n];
cout << "Input : " << endl;
cin >> ch;
cout << convert(ch,strlen(ch)) << endl;
return 0;
}
I wanted to convert an array of chars to a string value in thsi code.when i compiled ,there were no errors and it worked but program adds a random character to the final string .
For example:
Last edited on Jul 13, 2010 at 2:02pm UTC
Jul 13, 2010 at 2:09pm UTC
strings are null terminated in C/C++. You need to reserve space and add a null terminator to the end of kar in convert method.
Change following line
char *kar = new char [len];
to
char *kar = new char [len+1];
add following after
kar[len] = 0;
Jul 13, 2010 at 2:21pm UTC
You never delete kar, so that function leaks memory all over the place.
How it should be done:
1 2 3 4
string convert(char kter[],int len)
{
return string(kter,kter+len);
}
Or still far better: don't use char arrays at all.
Last edited on Jul 13, 2010 at 2:21pm UTC
Jul 13, 2010 at 2:32pm UTC
Athar .It is a smart way to do this .can you explain it briefly
Jul 13, 2010 at 2:42pm UTC
Last edited on Jul 13, 2010 at 2:43pm UTC