I want to assign the result of this code into a 2D array, I tried to save the result from the first output of the program in a file, and later on I will re open the file to assign the values in to the array, so I can use the array to get the result of the distance function…Unfortunately, when I defined the array as “int data[100][2]” Ican't use the “getline(myfile,line)”…because its work with a string values not int, is there any other way to do it correctly ? Any suggestions to make the this part better or more simple would be much appreciated
#include<iostream>
#include<string>
#include <fstream>
#include<cmath>
using namespace std;
int main() {
/// to find the nodes in each 100*100 gride///
int x, y, Radio_Range = 80, No_Max = 100;
int node_degree[100], data[100][2];
int Total_Degree = 0, Avg_Degree;
ofstream myfile;
myfile.open("example.txt");
int miny = 0, max_y = 99;
for (int i = 0; i < 5; i++) {
int minx = 0, max_x = 99;
for (int j = 0; j < 5; j++) {
for (int k = 0; k <= 4; k++) {
x = minx + rand() % (max_x - minx + 1);
y = miny + rand() % (max_y - miny + 1);
myfile << x << " " << y << endl;
}
minx = max_x + 1;
max_x = max_x + 100;
}
miny = max_y + 1;
max_y = max_y + 100;
}
///to finde the node degree//the avg degree//the distance///
int loop = 0; //Index of array//The line taken from the *.txt source
string line;
if (myfile.is_open()) { //Checking if the file can be opened
while (!myfile.eof()) { //Runs while the file is NOT at the end
getline(myfile, line); //Gets a single line from example.txt
data[loop][2] = line; //Saves that line in the array
loop++;
for (int i = 0; i < No_Max; i++) {
for (int j = 0; j < No_Max; j++) {
double distance = sqrt(
pow(data[i][0] - data[j][0], 2) +
pow(data[i][1] - data[j][1], 2));
if (distance <= Radio_Range) {
node_degree[i] = node_degree[i] + 1;
}
cout << data[i][0] << "-" << data[i][1] << endl;
cout << data[j][0] << "-" << data[j][1] << endl;
myfile << " The node degree \n" << node_degree[i] << endl;
}
}
for (int i = 0; i < No_Max; i++) {
Total_Degree = Total_Degree + node_degree[i];
Avg_Degree = Total_Degree / No_Max;
myfile << " The Avg degree\n" << Avg_Degree << endl;
}
myfile.close();
}
}
}
data[loop][2]
There is no column #2. Indices in C++ are zero-based.
您可能需要对数据进行类型转换,以匹配要为其分配数组的变量类型。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.