c++ - 使用循环创建条形图
问题描述
我的任务是使用输入文件创建条形图。它应该看起来像这样:
1930:***
1950: ******
1970 *****
etc
我把所有的东西都写好了,但它一直显示这样的东西:
1930
1950
1970
: ***
:******
:****
我似乎无法让它们正确显示。到目前为止,这是我的代码:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
//variables
int inputNum;
int year;
ifstream inputFile;
inputFile.open("People.txt");
if (!inputFile) // file did not open
{
cout << "Input file did not open" << endl;
return 10;
}
for (int year = 1910; year <= 2010; year += 20)
cout << year << endl;
while (inputFile >> inputNum)
{
for (int counter = 0; counter < (inputNum / 1000); counter++)
{
cout << "*";
}
cout << endl;
}
return 0;
}
解决方案
这可以很容易地完成std::map
#include <iostream>
#include <fstream>
#include <string>
#include <map>
int main() {
std::fstream input_file("test.txt");
std::map<int, int> years;
std::string temp;
while(input_file >> temp){
//add if it doesnt exist, otherwise, increment it
(years.find(std::stoi(temp)) == years.end()) ? years[std::stoi(temp)] = 1 : years[std::stoi(temp)]++;
}
for(auto i = years.begin(); i != years.end(); i++){
std::cout << i->first << ": ";
for(int j = 0; j < i->second; j++){
std::cout << "*";
}
std::cout << "\n";
}
return 0;
}
示例 txt 文件:
1930
1930
1930
1950
1950
1950
输出:
1930 ***
1950 ***
这将需要文件中的任何年份,如果您只想要某些年份,您可以轻松地添加额外的语句来检查
推荐阅读
- sql - 我怎样才能得到这样的桌子?
- ios - 如何修复 cocoapods 中丢失的资产
- javascript - Node/JS 回调函数放置
- java - 哈希映射
>,arraylist 不会存储值 - mongodb - 填充没有 _id
- javascript - JQuery/Javascript-Doc Ready 函数与上次加载的脚本文件/加载顺序有关吗?- 新手问题
- debugging - Redmi note 6 pro 设备无法在 android studio 中进行调试
- stackdriver - 如何将旧数据添加到 GCP stackdriver 上新创建的指标中?
- python - CGI - HTML 到 python
- assembly - 操作数必须是可重定位的程序集 x86 问题