I am new to C++ programming. I have a string and an integer and I want to merge them into one char array and after that I want to split it and get the string and the integer. I worked a piece of code and it almost works. The only problem is that it sometimes creates some garbage at the end of the string. I searched this forum but I didn't get a suitable solution. What am I doing wrong? Is there a simpler solution? Thank you in advance. Here is my code:
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main() {
cout << "string: ";
char my_string[64];
cin >> my_string;
int i = 666;
char i_size[8];
sprintf( i_size, "%9d", i );
strcat( my_string, i_size );
cout << my_string << endl;
char temp1[9] = { 0 };
strncpy( temp1, my_string + ( strlen( my_string ) - 9 ), 9 );
int in = atoi( temp1 );
cout << "int = " << in << endl;
char temp2[strlen( my_string ) - 9];
strncpy( temp2, my_string, strlen( my_string ) - 9 );
cout << "string = " << temp2 << "|" << endl;
return 0;
}
And here is the output:
[corneliu@localhost prog-build]$ ./prog
string: e
e 666
int = 666
string = e|
[corneliu@localhost prog-build]$ ./prog
string: wewewewe
wewewewe 666
int = 666
string = wewewewe�@|
[corneliu@localhost prog-build]$
cin >> my_string;this is UNSAFE. Either specify the maximum amount to read viacin >> setw(64) >> my_string;(via<iomanip>) or even better: use astd::stringfrom<string>. (Oh, and there are more of them:sprintfandstrcat.)char temp2[strlen( my_string ) - 9];this -- variable length arrays -- is a gcc extension, or C99, or C++1y, but not currently allowed in C++ (98/03/11). Even in C++1y, I'd rather say it's not recommended. Eitherstd::stringorstd::vectoror evennew char[strlen(my_string)-9]should be better.char temp2[strlen( my_string ) - 9];. It seems to me the space for the terminating\0is missing in the array. Note:strncpydoes not terminate the destination with a\0if the buffer is too small.