Generate Next Number and add to char*
Jun 6, 2017 at 9:58pm UTC
Hello!
I've tried to create a simple program that would allow me to increment a current integer and replace the last "n characters" in a char*.
However, no matter what I do, it simply outputs the same thing all over.
e.g Index = 1
Output:
XX160001
XX160002
XX160003
XX160004
...
XX160010
Could someone possibly tell me what am I doing wrong here?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include<iostream>
using namespace std;
int index = 1;
char * GenerateNext()
{
char * def = new char [9];
char buffer[9];
int counter = 0;
int temp = index;
while (temp != 0)
{
temp /= 10;
counter++;
}
strncpy_s(def, 9, "XX160000" , 8 - counter);
_itoa_s(counter, buffer, 9, 10);
strcat_s(def, 9, buffer);
index++;
return def;
}
int main()
{
char * generated = GenerateNext();
char * generated2 = GenerateNext();
cout << generated << endl << generated2 << endl;
for (size_t i = 0; i < 50; i++)
{
cout << GenerateNext() << endl;
}
delete [] generated;
delete [] generated2;
generated = nullptr ;
generated2 = nullptr ;
system("PAUSE" );
return 0;
}
Jun 7, 2017 at 9:03am UTC
It looks like I have set "_itoa_s" to check the counter (which gets set to 0 on every function call) and that's why it will always print the same number. After replacing "counter" with "index" inside _itoa_s, it seems to have fixed the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include<iostream>
using namespace std;
int index = 1;
char * GenerateNext()
{
char * def = new char [9];
char buffer[9];
int counter = 0;
int temp = index;
while (temp != 0)
{
temp /= 10;
counter++;
}
strncpy_s(def, 9, "XX160000" , 8 - counter);
_itoa_s(index, buffer, 9, 10);
strcat_s(def, 9, buffer);
index++;
return def;
}
int main()
{
char * generated = GenerateNext();
char * generated2 = GenerateNext();
cout << generated << endl << generated2 << endl;
for (size_t i = 0; i < 50; i++)
{
cout << GenerateNext() << endl;
}
delete [] generated;
delete [] generated2;
generated = nullptr ;
generated2 = nullptr ;
system("PAUSE" );
return 0;
}
Last edited on Jun 7, 2017 at 9:04am UTC
Topic archived. No new replies allowed.