1

I am trying to parse through a text file and have it output the contents onto the console with formatting by using setw(). My problem is that only the first row is formatted correctly, with the rest defaulting back to the left.

while (test) 
{
    cout << setw(20) << right;
    string menu;
    price = 0;

    getline(test, menu, ',');
    test >> price;

    cout << setw(20) << right << menu;;

    if (price)
        cout << right << setw(10) << price;


}

My goal is to get the output to align to the longest word (which is 20 spaces in length) on the right, but my output is ending up like this:

           WordThatAlignsRight
notAligning
my longest sentence goal align
notAligning

I am wanting each sentence to right align 20 spaces throughout the loop. Any help is appreciated, thanks!

bborokC
  • 29
  • 3
Jaws88
  • 21
  • 1
  • 8

1 Answers1

7

std::setw only works on the next element, after that there is no effect. For further information pls follow this link..

The code on the linked site will show you very clearly how std::setw works.

#include <sstream>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "no setw:" << 42 << '\n'
              << "setw(6):" << std::setw(6) << 42 << '\n'
              << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
    std::istringstream is("hello, world");
    char arr[10];
    is >> std::setw(6) >> arr;
    std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \""
              << arr << "\"\n";
}

Output:

no setw:42
setw(6):    42
setw(6), several elements: 89    1234
Input from "hello, world" with setw(6) gave "hello"
skratchi.at
  • 1,151
  • 7
  • 22