簡體   English   中英

在C ++中從文本文件讀取后如何求和值?

[英]How do you sum the values after reading from text file in C++?

我試圖弄清楚如何對從隨機數生成器生成的值求和。

在我的代碼下面,寫入並讀取隨機數,然后輸出所有隨機數。

我根本無法弄清楚如何將隨機數生成的值相加。

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>

using namespace std;

class Array
{
public:
    void Arrayoutput()
    {
        string array[1000]; // creates array to hold names
        short loop=0; //short for loop for input
        string line; //this will contain the data read from the file

        ifstream myfile ("Asg4.txt"); //opening the file.

        if (myfile.is_open()) //if the file is open
        {
            while (! myfile.eof() ) //while the end of file is NOT reached
            {
                getline (myfile,line); //get one line from the file
                array[loop]= line;
                cout << array[loop] << endl; //and output it
                loop++;
            }

            myfile.close(); //closing the file
        }
        else cout << "Unable to open file"; //if the file is not open output
    }
};

int main()
{
    Array Array1;
    ofstream myfile;

    myfile.open ("Asg4.txt");

    for (int i = 0; i < 1000; i++) //random number generator
    {
        myfile << 1+(rand()%1000) << endl;
    }
    myfile.close();

    Array1.Arrayoutput();

    return 0;
}

這是從文件中讀取數字並將其相加的方法

ifstream myfile ("Asg4.txt"); //opening the file.
int total = 0;
int number;
while (myfile >> number)
    total += number;
cout << "The total is " << total << "n";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM