我的任务是使用输入文件创建条形图。它应该看起来像这样:
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;
}
答案 0 :(得分:0)
此行:
cout << year << endl;
最后不需要endl
。删除它,这样就可以了:
cout << year;
答案 1 :(得分: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 ***
这将花费文件中的任何年份,如果您只想要某些年份,则可以轻松地添加额外的语句进行检查