简体   繁体   中英

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;
}

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';
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM