FriedRike
FriedRike

Reputation: 145

putting an integer into a string

I'm trying to put an integer into a string by separating its digits and putting them by order in a string of size 3

this is my code:

char pont[4];
void convertInteger(int number){
int temp100=0;
int temp10=0;
int ascii100=0;
int ascii10=0;
if (number>=100) {
    temp100=number%100;
    ascii100=temp100;
    pont[0]=ascii100+48;
    number-=temp100*100;
    temp10=number%10;
    ascii10=temp10;
    pont[1]=ascii10+48;
    number-=temp10*10;
    pont[2]=number+48;
}
if (number>=10) {
    pont[0]=48;
    temp10=number%10;
    ascii10=temp10;
    pont[1]=ascii10+48;
    number-=temp10*10;
    pont[2]=number+48;
}
else{
    pont[0]=48;
    pont[1]=48;
    pont[2]=number+48;
}
}

here's an example of what's suppose to happen:

number = 356

temp100 = 356%100 = 3

ascii100 = 3

pont[0]= ascii100 = 3

temp100 = 3*100 = 300

number = 365 - 300 = 56

temp10 = 56%10 = 5

ascii10 = 5

pont[1]= ascii10 = 5

temp10 = 5*10 = 50

number = 56 - 50 = 6

pont[2]=6

I might have an error somewhere and not seeing it (don't know why) ... This is suppose to be C++ by the way. I might be mixing this up with C language... Thanks in advance

Upvotes: 1

Views: 1998

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24164

All built-in types know how to represent themselves to std::ostream. They can be formatted for precision, converted to different representations, etc.

This uniform handling allows us to write built-ins to the standard output:

#include <iostream>

int main()
{
    std::cout << 356 << std::endl; // outputting an integer
    return 0;
}

Output:

356

We can stream to more than just cout. There is a standard class called std::ostringstream, which we can use just like cout, but it gives us an object which can be converted to a string, rather than sending everything to standard output:

#include <sstream>
#include <iostream>

int main()
{
    std::ostringstream oss;
    oss << 356;

    std::string number = oss.str(); // convert the stream to a string

    std::cout << "Length: " << number.size() << std::endl;
    std::cout << number << std::endl; // outputting a string
    return 0;
}

Output:

Length: 3
356

Upvotes: 1

sarnold
sarnold

Reputation: 104110

Probably the mistake that you're overlooking right now:

    pont[2]=number+48;
}
if (number>=10) {    /* should be else if */
    pont[0]=48;

However, I'd like to suggest a different approach; you don't care that the value is above 100, 10, etc., as 0 is still a useful value -- if you don't mind zero-padding your answer.

Consider the following numbers:

int hundreds = (number % 1000) / 100;
int tens = (number % 100) / 10;
int units = (number % 10);

Upvotes: 1

Related Questions