Converting from int to CString

6.7k views Asked by At
TestString::TestString(int num) 

This is a conversion constructor that should convert an integer to a string.

For example, if 123 is passed in, the TestString object should store the string data that would be represented by the c-string "123".

class TestString //header file
{
   public:
   TestString (int num);
   //etc.

   private:
   int size;
   char* str;
};

TestString::TestString (int num) //.cpp file 
{
    char c = static_cast<char>(num);

    str = new char[size]; //missing size variable

    int i = 0;

    for (i; cstr[i] != '\0'; i++) //missing cstr array
        str[i] = cstr[i];

    str[i] = cstr[i]; //to tack on null character
}

As you can tell I am missing both the size variable and cstr string in the definition. I don't know if I'm going about this all wrong or just having trouble understanding what sort of setup I'm being asked for...

Any pointers or suggestions greatly appreciated.

Only libraries permitted:

#include <iostream>
#include <iomanip>
#include <cstring>
#include <cctype>
2

There are 2 answers

1
acenturyandabit On BEST ANSWER

So by what I understand you want to get the length required for the output string. I guess the only way to do that without <cmath> is using a while loop as such:

int len=0;
int num2=num;
do{
    num2=num2/10;
    len++;
} while (num2>0);

which basically keeps dividing the number by 10 to get how many digits it has.

Then, for each character you can do this: Say you want the character for 0, just use '0'. If you want the character for '1', use '0'+1 which will return 1.

If you need any more help (a full implementation), just comment below and I'll get to you. Have fun!

0
David Haim On

you don't need any other things than pure vanilla C++ , just use std::to_string:

std::string ouputString = std::to_string(inputInteger);

now you can pull out C-string with std::string::c_str:

ouputString.c_str()