0

I got a quick question for the following code

int main()
{
    string data;
    int x;
    cin >> x;

    if (x < 0)
    {
        data = to_string(x);
    }
    else
    {
        data = to_string(x);
    }
   return 0;
}

If I does not want to use to_string(x), instead I want to do something manually. Is there anyway I can do that? If I use data = x; this obviously won't work.

ps. I doesn't want to use atoi either,

0

5 Answers 5

1

You can do the following:

int main(){
    int x;
    cin>>x;
    string s = "";     // s will represent x but with the digits reversed
    bool neg = 0;      // this flag is 1 if x is negative and 0 if positive. 
                       // we will use it to find out if we should put a "-" before the number
    if(x < 0){
        neg = 1;
        x *= -1;       // making the number positive
    }
    while(x){
        char c = '0' + x % 10;          // c represent the least significant digit of x
        s.push_back(c);                 // adding c to s             
        x /= 10;                        // removing the least significant digit of x
    }
    string ans = "";                    // ans is our resulting string
    if(neg) ans.push_back('-');         // adding a negative sign if x was negative
    for(int i=s.size() - 1; i >= 0; i--)    // adding the characters of s in reverse order
        ans.push_back(s[i]);
}
Sign up to request clarification or add additional context in comments.

5 Comments

If std::to_string doesn't qualify as "manually", I don't see how this would.
Sorry, I did not pay attention. I will modify my code.
What is the reason to put the digit in reversed order?
x%10 will return an integer between 0 and 9. but we need a character to represent the integer. And in the ASCII table (en.wikipedia.org/wiki/ASCII) we have the sequence of digits come in sequence starting with 0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). So if we add to the ASCII value of '0' an integer x between 0 and 9 we will get a character with the ASCII value representing the integer x.
x%10 returns the least significant digit of x. So 123%10 will return 3. And we are saving 3 in s[0], but in the final string 3 should be in the last index.
1

This might be sufficient.

string convertInt(int number)
{
    if (number == 0)
        return "0";
    string temp="";
    string returnvalue="";
    while (number>0)
    {
        temp+=number%10+'0';
        number/=10;
    }
    for (int i=0;i<temp.length();i++)
        returnvalue+=temp[temp.length()-i-1];
    return returnvalue;
}

(I did not write this function, but found it by doing a quick Google search. The original post is here.)

This function works by dividing the number by 10. It takes the remainder of the division, which will always be between 0 and 9. It then "finds" the character representing that number by adding the integral value of the character 0 to it.

Next, it takes the quotient of that division, and performs the same operation again and again until the quotient is zero.

This results in a string that contains the characters representing the number, but in reverse order. The final loop reverses the string before returning it.

As chris points out in the comments below, the digits 0 through 9 are guaranteed to be in sequential order

N3485, §2.3 [lex.charset]/3: In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. (the above list is, quite intuitively, 0 1 2 3 4 5 6 7 8 9).

Here is good reading material about string manipulation: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

7 Comments

Not sure why the down vote. This does as the OP asked, without really calling another function to accomplish the job.
I didn't down-vote, but can see why it was. The code assumes a particular character set (ASCII) and will not work with others. There are much less cryptic ways to do the job as well.
Rather than giving a warning that it won't work with other character sets while using a number that is hard to understand unless you know '0' is 48 in ASCII, why not just use '0'? '0' through '9' are guaranteed to be consecutive in the character set, '0' conveys meaning a lot better, and now the code works portably (not that depending on ASCII really makes a difference for 99% of code).
It's possible the other digits aren't simply the next 9 characters, and it could still fail.
@Steve, Sorry, edited my comment, but they are indeed. Even if they weren't, you get the benefit of more readability with that same assumption, and no more '0' being 48 assumption.
|
0

Formatting an integer manually in any number base isn't hard. E.g. in base 10:

void print(int n)
{
    if (n == 0) { std::cout << '0'; return; }
    if (n < 0) { std::cout << '-'; n = -n; }

    std::string buf;
    while (n != 0) { buf += '0' + n % 10; n /= 10; }
    for (auto it = buf.rbegin(); it != buf.rend(); ++it)
        std::cout << *it;
}

If your number base is larger than ten, you'll have to provide a suitable alphabet and use n % base to enumerate the desired digit.

If you want to avoid reallocations, you can reserve capacity in the string, and you can compute the required capacity by taking a suitable logarithm of n.

Comments

0

If you really must extract the digits yourself

std::string manual_convert(int value)
{
    if (x < 0)
       return std::string("-") + manual_convert(-x);   // handle negative values (except potentially INT_MIN)
    else if (x == 0)
       return "0";

    std::string retval;
    while (x > 0)
    {
         char digit = x%10 + '0';     // extract the proverbial digit
         retval.append(1, digit);
         x /= 10;                     // drop the digit, and prepare for next one
    }

    std::reverse(retval.begin(), retval.end());   // loop above extracted digits in reverse order
    return retval;
}

Comments

0

Two easy ways:

#include <sstream>
string intToString(int x)
{
   stringstream stream;
   stream << x;
   return stream.str();
}

Or if you using boost library

string str = lexical_cast<string>(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.