我想将此代码的结果分配到2D数组中,我试图将程序的第一个输出的结果保存到文件中,稍后我将重新打开文件以将值分配给数组,所以我可以使用数组来获取距离函数的结果...不幸的是,当我将数组定义为“int data [100] [2]”时我不能使用“getline(myfile,line)”...因为它的工作字符串值不是int, 有没有其他方法正确地做到这一点? 任何使这部分变得更好或更简单的建议都将非常感激
#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();
}
}
}
答案 0 :(得分:0)
data[loop][2]
没有第2列。 C ++中的索引是从零开始的。
答案 1 :(得分:-1)
您可能需要对数据进行类型转换以匹配您为其分配的数组的变量类型。