【问题标题】:program is being crashed while trying to read something from file in c++ [closed]程序在 C++ 中尝试从文件中读取内容时崩溃 [关闭]
【发布时间】:2016-10-30 16:03:06
【问题描述】:

假设,我有两个名为 file1.txt 和 file2.txt 的文本文件。文件格式如下:

文件1:

1    0.1
2    0.2
3    0.3 

文件2:

1    0.1
2    0.2
3    0.3 

每个文件的第一列是演员编号,第二列包含它们对应的值。我想将两个文件的所有参与者的所有值存储在一个二维数组中。我制作了以下 c++ 代码来执行此操作:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<fstream>
#include <sstream>
#include<cmath>
using namespace std;

#define actor 3

std::string to_string(int i) {
   std::stringstream s;
   s << i;
   return s.str();
}


int main()
{
    FILE *fp,*fp1;
    int SIN=2  // total file number
    double dynamicity_SIN [SIN][actor+1]; // 2D array that will contain the values of each actor of both the files
    for(int i=1;i<=SIN;i++)
    {
         for(int j=0;j<actor;j++)
         {
               dynamicity_SIN[i][j+1]=0;
         }
     }


  string fileName2;
  string name1 = "file";  
  string name2 = ".txt";
  int k1;
  double k3;
  int i=1;
  while(i<=SIN)
{
    fileName2 = name1+to_string(i)+ name2;
    fp1=fopen(fileName2.c_str(),"r");

        while(fscanf(fp1, "%d", &k1) != EOF)
        {
            fscanf(fp1, "%lf", &k3);
            dynamicity_SIN[i][k1]=k3;

        }

        i++;
        fclose(fp1);
    }

} 

但是程序在进入 while 循环之前就崩溃了。代码有什么问题吗?

【问题讨论】:

  • 数组是从0开始的,你访问dynamicity_SIN数组越界
  • for(int i=1; i for( int i=0; i

标签: c++ arrays file multidimensional-array


【解决方案1】:

在所有循环中,您都从索引 1 开始访问数组。 当你定义一个数组时:int* array=new int[5],你应该只访问array[0]array[4]

所以你的循环应该是这样的:

for(int i=0;i<5;++i){
   some code with array[i]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2020-12-07
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    相关资源
    最近更新 更多