【发布时间】: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