c++ - 如何在C++中为二维数组赋值

标签 c++ visual-c++

我想将这段代码的结果赋值到一个二维数组中,我试图将程序第一次输出的结果保存在一个文件中,稍后我将重新打开文件将值赋值到数组,所以我可以使用数组来获取距离函数的结果……不幸的是,当我将数组定义为“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();
        }
    }
}

最佳答案

data[loop][2]

没有第 2 列。 C++ 中的索引是从零开始的。

关于c++ - 如何在C++中为二维数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13239891/

相关文章:

c++ - (部分)特化依赖类型的非类型模板参数

c++ - 如何解锁Windows登录屏幕

c++ - 为什么以下正则表达式代码在 VC++ 2013 Debug模式下崩溃

c++ - 专用版本是否可以与原始模板类共享某些功能?

c++ - BOOST_FUSION_ADAPT_TPL_STRUCT 与模板成员

java - 在屏幕上非线性滑动

c++ - 使用ffmpeg编码: video quality drops

c++ - 在 IE 中 fork 或复制用户浏览器 session

javascript - Windows 商店应用程序的语言选择 : C++ or javascript ?

c++ - 指向更大 unsigned char 数组的每个第 n 个元素的指针数组