【问题标题】:How do you sum the values after reading from text file in C++?从 C++ 中的文本文件读取后,如何对值求和?
【发布时间】:2019-02-09 07:40:38
【问题描述】:

我想弄清楚如何对随机数生成器生成的值求和。

下面我的代码写入随机数并读取它,并输出所有随机数。

我根本不知道如何对随机数生成的值求和。

#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;
}

【问题讨论】:

标签: c++ computer-science


【解决方案1】:

这是从文件中读取数字并将它们相加的方法

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

【讨论】:

  • 你甚至可以取消手动循环:int total = std::accumulate(std::istream_iterator&lt;int&gt;(myfile), std::istream_iterator&lt;int&gt;(), 0);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 2020-02-24
相关资源
最近更新 更多