user1815798
user1815798

Reputation:

Using setw and left from iomanip

I want to print out the keys and values in a map in a organized table. I am trying to use setw and left but the output is

The  1
hello1

and I want it to be like

The     1
hello   1

what i have done so far

// System includes

#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
#include <unordered_map>
#include <fstream>
#include <iomanip>

/************************************************************/

Local includes

/************************************************************/
// Using declarations

using std::cout;
using std::map;
using std::unordered_map;
using std::string;
using std::cin;
using std::endl;
using std::ifstream;
using std::left;
using std::setw;

/************************************************************/

Function prototypes/global vars/typedefs

/************************************************************/

int
main (int argc, char* argv[])
{

    //call the wordCount function on the user specified input file
    unordered_map <string,int> exampleMap;
    exampleMap["The"]++;
    exampleMap["hello"]++;

    cout << left;
    //iterate through the map and print out the elements
    for( unordered_map<string, int>::iterator i=exampleMap.begin(); i!=exampleMap.end(); ++i)
    {
      cout << setw(5) << (*i).first << setw(15) << (*i).second << endl;
    }

    return EXIT_SUCCESS;
}

Upvotes: 2

Views: 1022

Answers (1)

NullPoiиteя
NullPoiиteя

Reputation: 57322

you need to specify a width larger than 5(If you want the field to be larger than 5 characters). You don't need the second call to setw.

try

 for( auto i=exampleMap.begin(); i!=exampleMap.end(); ++i)
     {
        cout << setw(8) << i->first << i->second << '\n';
      }

Upvotes: 2

Related Questions