MadelineStates
MadelineStates

Reputation: 31

How to display char character as an int, not as the ASCII symbol

I need this character to display as a number but I keep getting smiley faces and hearts and other ASCII symbols. This part is where I think the problem is:

 s = prefix + ch + '.';

And here's the whole code:

int main()
{
    int levels = 2;
    string prefix = "Recursion:";

    sections(prefix, levels);

    system("pause");
    return 0;
}

void sections(string prefix, int levels)
{
    if (levels == 0)
    {
        cout << prefix << endl;
    }
    else
    {
        for (char ch = 1; ch <= 9; ch++)
        {
            string s;
            s = prefix + ch + '.';
            sections(s, levels - 1);
        }
    }
}

Upvotes: 0

Views: 150

Answers (3)

Max Shuu
Max Shuu

Reputation: 63

The problem is your for-loop

char ch = 1 //is not a 1
char ch = '1' //instead is (but i'm not sure if you can increment this)
char ch = 49 // is also a 1

hope that helps.

https://en.wikipedia.org/wiki/ASCII

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126378

You're using int values for your characters, rather than characters, so you will get whatever characters happen to have those codes in your character set. Use ' arounds a character to get the character code for a specifiec character:

for (char ch = '1'; ch <= '9'; ch++)
    sections(prefix + ch + '.', levels - 1);

Note that this depends on the digit characters all being contiguous and in ascending order in your character set (implementation defined), but that is the case for every character set I can think of...

Upvotes: 2

Andrey Nasonov
Andrey Nasonov

Reputation: 2629

You should use std::to_string function to convert the number into string.

Upvotes: 0

Related Questions