将随机数据写入文本文件



我正在创建一个程序,生成给定数量的随机数据行,每行有10个从-50到50的随机int值。最后一列是行值的和。

我有麻烦写随机数据到一个文本文件。当我运行它时,最后一列似乎是唯一的问题。

我是新手,所以请原谅我。

到目前为止,这是我的程序:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
//function prototype
void writeData(int, int);
int main() {
int ROWS;
const int COLS = 10;
cout << "Enter number of rows (10-25): ";
cin >> ROWS;
writeData(ROWS, COLS);
return 0;
}//end main

void writeData(int ROWS, const int COLS) {
//Create an array with column count.
int arr[ROWS][COLS];

//Seed the random number generator.
srand((unsigned)time(0));

//Create and open a file.
ofstream outputFile;
outputFile.open("myfile.txt");
//Generate a random number (between 10 and 25) of rows of random data.
//Write random data to file.

outputFile << "[" << ROWS << ", " << COLS+1 << "]n";

int sum = 0;
for(int i=0; i<ROWS; i++) {
for(int j=0; j<COLS; j++) {
arr[i][j] = (rand()%50)+(-50);       //each row has 10 random integer values between -50 and 50
outputFile << ((int) arr[i][j]) << "t";
sum += arr[i][j];   //sum row values
}
outputFile << arr[i][COLS] << sum << endl;  //store row sum in last column in the row
sum = 0;   //reset sum to 0
}

//Close the file.
outputFile.close();

//Confirm the data is written to file.
cout << "The data was saved to the file.n";
}//end writeData

我得到这个输出:

[10, 11]
-5  -7  -28 -48 -12 -2  -29 -28 -40 -18 0-217
-49 -11 -15 -20 -34 -40 -25 -46 -41 -42 1430822061-323
-3  -13 -27 -24 -13 -29 -44 -25 -43 -2  764375682-223
-43 -37 -32 -40 -26 -29 -30 -32 -22 -24 0-315
-31 -12 -2  -12 -38 -15 -27 -36 -24 -21 71091072-218
-11 -49 -48 -47 -10 -44 -32 -22 -31 -7  -343595632-301
-32 -17 -28 -34 -48 -46 -29 -9  -17 -13 0-273
-22 -46 -25 -3  -34 -14 -2  -32 -7  -22 400-207
-5  -13 -13 -14 -17 -47 -28 -19 -5  -36 10-197
-3  -1  -27 -4  -30 -43 -47 -20 -13 -16 -343595600-204

我已经走了这么远的试验和错误。现在,我被困住了。如果能给点指导,我将不胜感激。

关于你的程序有几件事:

  • 如果您想创建[-50,+50]中的数字,请将(rand()%50)+(-50)更改为rand()*100-50

  • 如果你不重用int arr[ROWS][COLS];做任何事情:只要删除它。

  • 声明int sum=0;在正确的位置(内循环)

  • 不要把arr[i][COLS](这也是一个越界错误,因为你超过了arr的大小)放入你的outputFile。

所以正确的函数应该是:

void writeData(int ROWS, const int COLS) {
//Seed the random number generator.
srand((unsigned)time(0));
ofstream outputFile;
outputFile.open("myfile.txt");
outputFile << "[" << ROWS << ", " << COLS+1 << "]n";
for(int i=0; i<ROWS; i++) {
int sum = 0;
for(int j=0; j<COLS; j++) {
int const value = rand()*100-50;
outputFile << value << "t";
sum += value; 
}
outputFile << sum << endl;  //store row sum in last column in the row
}
outputFile.close();
}//end writeData

最新更新