c++ - 使用用户创建的输出文件中的两个变量计算总和

标签 c++

我正在尝试弄清楚我将如何使用我创建的输出文本文件来计算两个变量的总和。我的输出文本文件正确保存了信息,但我的总和为 0 和 0,因此它没有读取我认为的信息。另外,我输入数组的信息是否只保存到文本文件中?我只需要将它保存到文本文件中,这样总和计算就只从文本文件中接收信息

#include <iostream>
#include <string>
#include<iomanip>
#include <fstream>


using namespace std;

int main() {
int ItemNumber[2];
float price[2];
int sumnumber = 0;
float   sumprice = 0;
string myfile = "c:/Users/rz/Desktop/numbers.txt";

int count = 0;


ofstream outFile;
outFile.open(myfile);
while (count <= 1)
{
    cout << "enter a price" << endl;
    cin >> price[count];
    outFile << price[count] << endl;
    cout << "enter a item number" << endl;
    cin >> ItemNumber[count];
    outFile << ItemNumber[count] << endl;

    count++;
}

outFile.close();


fstream inFile;
inFile.open(myfile);
while (count <= 1)
{

    sumprice = sumprice + price[count];

    sumnumber = sumnumber + ItemNumber[count];
}
cout << sumnumber << endl;
cout << sumprice << endl;
system("pause");
    return 0;
}

最佳答案

在第一个循环结束时:

int count = 0;
while (count <= 1) { ... count++ ... }

变量 count 将被设置为 2

然后,当你开始第二个循环时:

while (count <= 1) ...

条件已经为假,因此永远不会执行循环体。

为了让它工作,您必须将计数重置为零,以便它再次运行项目。或者,更好的是,单独保留 count(因为它表示处理了多少项目)并使用另一个变量来处理它们:

for (int i = 0; i < count; ++i) { ... use i rather than count ... }

关于c++ - 使用用户创建的输出文件中的两个变量计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339875/

相关文章:

c++ - 如何让 cmake 使用 "-pthread"而不是 -lpthread”?

c++ - 如何将 WM_KEYDOWN 消息传递给 IWebBrowser2 实例?

c++ - 如何检查输入是否有效?

c++ - 在 Ubuntu 20.04 上使用 nano 库时出现链接器问题

c++ - OpenGL宝典第5版代码问题

c++ - 为什么 iostream 包含 time.h?

c++ - MIXED_STR_LEN_ARG 与 gfortran

c++ - CascadeClassifier 检测的错误参数

c++ - VC++ 的一个大错误?为什么初始化列表不对结构进行值初始化?

c++ - 从 for 循环到另一个循环的变量