【发布时间】:2017-09-09 05:10:24
【问题描述】:
节目说明: 编写一个程序来读取名为 sales.dat 的数据文件。 然后程序应该显示一个条形图来比较每个商店的销售额,并将销售条形图输出到一个名为 results.dat 的文件中。 通过显示一行星号在条形图中创建每个条形。每个星号应代表 100 美元的销售额。
它在 Visual Studio 中使用了 2 个资源文件 sales.txt 和 results.txt。所以基本上,我的程序正常工作,我提交了我的作业。我今天重新打开它来弄乱它,它完全停止工作了。它似乎不是从 sales.txt 读取的。 sales.txt 每行只有随机整数。例如,1000、1200、1400。输出将在 results.txt 和控制台中的每一行上显示 10、12 和 14 个星号。
问题是它说 商店 1: 商店 2: 以此类推,但不显示星号。
int main() {
int storeAmount = 0;
double sales = 0.0;
int starAmount = sales / 100; //gets the amount of stars needed
ifstream inFile("sales.txt"); //opens the file sales.txt which is a resource file
ofstream outFile("results.txt"); //opens the file results.txt which is our output file
string outputStars = ""; //holds the stars for the bar graph
cout << "Please input the amount of stores:" << endl; //input the amount of stores
cin >> storeAmount;
cout << "SALES BAR CHART:" << endl; //header output
cout << "Each * = $100" << endl;
for (int storeNum = 0; storeNum < storeAmount; storeNum++) { //loops to the max store amount
inFile >> sales; //variable sales holds the value of each of the lines in sales.txt
for (int i = 0; i < starAmount; i++) { //adds stars onto the string
outputStars += "*";
}
cout << "Store " << storeNum + 1 << ": " << outputStars << endl; //ouputs in the console
outFile << "Store " << storeNum + 1 << ": " << outputStars << endl; //outputs to the file
if (inFile.eof()) { //stops the duplication of the last line if the store amount is greater than the numbers in sales.txt
break;
}
}
outFile.close(); //closes the files
inFile.close();
system("pause");
return 0;
}
【问题讨论】:
-
在阅读销售额之前无法计算starAmount。它永远是 0。
-
我是个白痴。 int starAmount = 销售额/100;需要在我从文件中输入销售额之后。
-
请正确缩进你的代码,它不会使它工作,但它至少可以使它可读....