C ++ Asterik Graph

时间:2016-12-08 20:47:15

标签: c++ vector graph

我最近创建了一个由asterik制作的图表,我需要在asterik旁边显示文字,如下所示:

SALES BAR CHART
(each * equals £100)
Store 1: **********
Store 2: *****
Store 3: ************
Store 4: ******
Store 5: **

这是我到目前为止编写的代码,我想知道是否可以对如何显示文本有一些指导。非常感谢。

#pragma once //stops duplicate library 

#include<iostream>
#include<string>
#include<fstream>
#include<vector>

using namespace std;

class SalesData
{
private:
    ifstream inputfile;
    ofstream outputfile;
    vector<int> salesrecord;

public:
    void loadDataFromFile(string filename);
    void saveBarChartToFile(string filename);
};

void SalesData::loadDataFromFile(string filename)
{
    int number;
    ifstream sales;
    sales.open("Sales.txt", ios::in);
    while (sales >> number)
    {
        salesrecord.push_back(number);
    }

    cout << "opening file." << endl;

    sales.close();
}

void SalesData::saveBarChartToFile(string filename)
{
    ofstream graph;
    graph.open("Graph.txt", ios::out);
    string stars;
    graph << "SALES BAR CHART" << endl;
    graph << " (each * equals £100)" << endl;

    for (int i = 0; i < salesrecord.size(); i++)
    {
        stars = "";

        for (int starcount = 1; starcount <= (salesrecord[i] / 100); starcount++)
        {
            stars += "*";
        }

        graph << stars << endl;
    }
    graph.close();
}

int main()
{
    SalesData Mydata;
    Mydata.loadDataFromFile("Sales.txt");
    Mydata.saveBarChartToFile("Graph.txt");

    return 0;
}

2 个答案:

答案 0 :(得分:0)

你可以改变

graph << stars << endl;

graph << "Store " << (i + 1) << ": " << stars << endl;

此更改将添加单词store,后跟数字。变量i增加1,因为i是基于零的索引,并且您表示要从1开始存储编号。

答案 1 :(得分:0)

首先,生成星星的整个循环可以使用带有整数和字符重复的std::string constructor (2)在一行中完成。

其次,您需要的是在打印星星之前打印的文字:

for (int i = 0; i < salesrecord.size(); i++)
{
    std::string stars(salesrecord[i] / 100, '*');
    graph << "Store " << i + 1 << ": " << stars << endl;
}