gpt4 book ai didi

c++ - 使用 setw 并从 iomanip 离开

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:53:22 25 4
gpt4 key购买 nike

我想在有组织的表格中打印出 map 中的键和值。我正在尝试使用 setw 和 left 但输出是

The  1
hello1

我希望它像

The     1
hello 1

到目前为止我做了什么

// System includes

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

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

本地包含

/************************************************************/
// 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;

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

函数原型(prototype)/全局变量/类型定义

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

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(如果你希望字段大于5个字符)。您不需要第二次调用 setw。

尝试

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

关于c++ - 使用 setw 并从 iomanip 离开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com