首页 > 解决方案 > 使用循环创建条形图

问题描述

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

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

标签: c++

解决方案


这可以很容易地完成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 ***

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


推荐阅读