[英]Writing random data to a text file c++
我正在創建一個程序,它生成給定數量的隨機數據行,每行有 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
我為 output 得到這個:
[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 中。
所以正確的 function 應該是:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.