Miller
Miller

Reputation: 182

Formatting Columns with cout and Strings

Good evening! I was hoping I might ask your assistance with formatting strings in a cout statement.

The goal is to have all columns align left with a max width of colWidth.

In the output below, you'll notice the column widths perform as desired unless the string length is below the column width (as with inventory item 3). If I replace the string(strArray[i].begin(), strArray[i].begin() + colWidth) with strArray[i], the exact opposite occurs where any string elements that are below the column max are fine, but anything else overflows and pushes out the text.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
    string strArray[20] = {"mumblemumble1","mumblemumblemumble2","mumble3","mumblemumblemumblemumble4","mumblemumblemumble5","mumble6","mumblemumblemumblemumble7","mumblemumblemumble8","mumble9","mumblemumblemumblemumble10","mumblemumble11","mumblemumblemumble12","mumble13","mumblemumblemumblemumble14","mumblemumblemumble15","mumblemumble16","mumblemumblemumble17","mumble18","mumblemumblemumblemumble19","mumblemumblemumble20"};
    int cols = 2;       // The number of columns to display
    int colWidth = 10;  // Width allowed for title output
    int colCount = 0;   // Used with mod (%) to provide a new line when needed

    cout << endl << endl << "Number of titles in inventory: " << 20;
    cout << endl << endl;

    for(int i = 0; i < 20; i++)
    {
        cout << setw(4) << right << (i + 1) << ") " << left << setw(colWidth) << string(strArray[i].begin(),strArray[i].begin() + colWidth);
        if ((i+1) % cols == 0)
            cout << endl;
    }

    return 1;
}

Produces the following output:

Number of titles in inventory: 20

   1) mumblemumb   2) mumblemumb
   3) mumble3   4) mumblemumb
   5) mumblemumb   6) mumble6
   7) mumblemumb   8) mumblemumb
   9) mumble9  10) mumblemumb
  11) mumblemumb  12) mumblemumb
  13) mumble13  14) mumblemumb
  15) mumblemumb  16) mumblemumb
  17) mumblemumb  18) mumble18
  19) mumblemumb  20) mumblemumb

Upvotes: 1

Views: 818

Answers (1)

MrMadsen
MrMadsen

Reputation: 3012

This code string(strArray[i].begin(),strArray[i].begin() + colWidth) throws an exception when the string is shorter than 10 characters ('mumble3' for example).

Change your for loop to this:

for (int i = 0; i < 20; i++)
{
    string str = strArray[i];
    while (str.size() < colWidth) {
        str = str + " ";
    }
    cout << setw(4) << right << (i + 1) << ") " << left << setw(colWidth) << string(str.begin(), str.begin() + colWidth);
    if ((i + 1) % cols == 0)
        cout << endl;
}

Upvotes: 2

Related Questions