我的问题是我如何添加到我的for循环,以便当它进行多次迭代时,变量将相互覆盖?For循环允许变量相互覆盖
我试图把一个输入文本文件与三元股份像这样:
*谷歌(GOOG)
522.01 2 100
520.66 1.5 80
苹果公司(AAPL)
389.27 2 150
401.82 1.8 1 50
微软(Microsoft)
25.06 2.5 100
25.07 2 80 *
再后来打印/写到输出文本文件。
现在,当它重复运行3次时,它只显示股票1及其正确的数字,但是错误的数字和其他名称都没有。那么,我将如何去做,以便下一次迭代将覆盖并打印另一组答案?
下面是对部分代码,我有:
for (int x = 1; x <= 3; x++) // for loop to run this part of program 3 times
{
getline(dataIn, stockName);//Gets the whole first line
dataIn >> buyingAMT;//These just store whatever is in the line before every space, and sets it with a name
dataIn >> buyingComm;//So like it takes the characters leading up to the first space and stores it as buyingAMT.
dataIn >> numberBought;
dataIn >> sellingAMT;
dataIn >> sellingComm;
dataIn >> numberSold;
//writing to a file
buyingComm = buyingComm * buyingAMT;//Mathematical Calculations
buyingAMT = buyingAMT * numberBought;
sellingComm = (sellingComm/100) * numberSold;
sellingComm = sellingComm * sellingAMT;
sellingAMT = sellingAMT * numberSold;
profit = (sellingAMT - sellingComm) - (buyingAMT + buyingComm);
//Displaying the calculated answers
fout << setw(20) << left << stockName;
fout << setprecision(2) << fixed << setw(15) << right << buyingAMT;
fout << setprecision(2) << fixed << setw(15) << right << buyingComm;
fout << setprecision(2) << fixed << setw(15) << right << sellingAMT;
fout << setprecision(2) << fixed << setw(15) << right << sellingComm;
fout << setprecision(2) << fixed << setw(15) << right << profit << endl;
//Storing the results into the overall variables to be used later
/*totalBuyingAMT += buyingAMT;
totalBuyingComm += buyingComm;
totalSellingAMT += sellingAMT;
totalSellingComm += sellingComm;
grandProfit += profit;
*/
}
getline(dataIn, junk);//Cleans the remaining unread data
dataIn.close();//closes the input file, so it cant be read any longer
fout.close();
cout << "congrats you are either now screwed or rich!";
return 1;
}
这可以帮助你。 https://stackoverflow.com/questions/20080255/mixing-formatted-input-extractors-with-getline-causes-cout-display-to-stick-toge P.S.请删除C#标签,它们不是一回事。 –
从'main'返回非零表示失败。 –