从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";
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 从C++中的文本文件中读取后如何对值求和
- 使用c++从文件中读取数据,并在击中特定行(字符串)后对特定列求和
- 编写一个函数从文件中读取数字并求和
- 从文件中读取数据到2d数组中,并使用c++对特定数组求和
- 如何读取矩阵并求和