使用循环创建条形图

Creating a bar chart using loops

本文关键字:条形图 创建 循环      更新时间:2023-10-16

我的分配是使用输入文件创建条形图。它应该看起来像这样:

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

此行:

cout << year << endl;

最后不需要endl。将其删除,这样您才有:

cout << year;

这可以用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 ***

这将需要文件中的任何一年,如果您只想要某些年份,就可以轻松地放置额外的语句来检查