A strange string problem

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:

Input : 
table
table'

Input : 
table
table3
Last edited on

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;
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
Athar .It is a smart way to do this .can you explain it briefly
This uses the last string constructor listed here:
http://www.cplusplus.com/reference/string/string/string/

It initializes the string with the specified character range.
As you can see, the fourth one is also suitable for this (return string(kter,len);).
Last edited on
Thank you for all...
Topic archived. No new replies allowed.