Wdoug
Wdoug

Reputation: 27

Cannot go to new line in text wrap

I don't know what I'm doing wrong and can't figure it out on my own.

void text_printer(char text[], int wrap_size)
{
    bool space_check;
    for (int sub = 0; text[sub] != '\0'; sub++)
    {
        space_check = false;

        if (sub % wrap_size == 0 && sub != 0)
            space_check = true;

        if (space_check == true && text[sub] == ' ')
        {
            cout << endl;
        }
        else
        {
            cout << text[sub];
        }
    }
}

The second if statement doesn't execute when it's supposed to.

ah yes you are here for tea

If I pass this to it, it won't change when it's outputted.

It compiles just fine and there are no errors so I assume it's a problem with my code, but I can't figure out what it is.

Upvotes: 0

Views: 74

Answers (2)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38440

You have a couple of troubles in your code. I will describe one of it. Another has been described by @artm. What if wrap_size is 9 an the input line is like "12345678901234567 12 45 78 01". Then your code is going to split it like

12345678901234567
12
45 78 01

I suppose it is not what you want and must be

12345678901234567
12 45 78
01

So the proper solution should be like bellow

void text_printer(char text[], int wrap_size)
{
    for (int sub = 0, count = 0; text[sub] != '\0'; sub++, count++)
    {
        bool space_check = count >= wrap_size; 
        if (space_check && text[sub] == ' ')
        {
            cout << endl;
            count = 0;
        }
        else
        {
            cout << text[sub];
        }
    }
}

Upvotes: 2

tdao
tdao

Reputation: 17668

It doesn't work because you have a flaw in this logic if (space_check == true && text[sub] == ' ') What happens when space_check == true but text[sub] isn't a space, now space_check will be reset to false on the next loop, and you will miss the new line.

This is one way to get your logic right. Add a new variable idx to keep track of how many characters have passed the last space character, then make sure to break the line (and reset idx for the next round).

int idx = 0;
for (int sub = 0; text[sub] != '\0'; sub++, idx++)
{
    space_check = false;

    if (idx >= wrap_size && sub != 0)
        space_check = true;

    if (space_check == true && text[sub] == ' ')
    {
        cout << endl;
        idx = 0;
    }
    else
    {
        cout << text[sub];
    }
}

Upvotes: 0

Related Questions