You are here:

C++/Wats the problem with my code?

Advertisement


Question
Hi,

I am reading a text file which has 4 columns into a 3D array.

My code is compiling........but cant see the output. Shows .exe file stopped working.

My code is as follows:

//#include "stdafx.h"
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

int function(const char *fName, int  img_3D[][128][128])
{
int a[5],i,j;
FILE *fp=fopen("abc.txt","r");
while(!feof(fp))
{
   cout<<"file opened";
 for(i=0;i<4;i++)
  fscanf(fp,"%d",&a[i]);
 if(feof(fp)) break;
 if(a[0]>126||a[1]>126||a[2]>126)
 {
  printf("Error in input");
  return(-1);
 }
 //printf("%d %d %d %d\n",a[0],a[1],a[2],a[3]);
 img_3D[a[0]+1][a[1]+1][a[2]+1]=a[3];
}
fclose(fp);
}

int print(const char *fName,int img_3D[][128][128])
{
int a[5],i,j,fee;
FILE *fp=fopen("abc.txt","r");
while(!feof(fp))
{
 for(i=0;i<4;i++)
  fscanf(fp,"%d",&a[i]);
 if(feof(fp)) break;
 if(a[0]>126||a[1]>126||a[2]>126)
 {
  printf("Error in input");
  return(-1);
 }
 printf("%d\n",img_3D[a[0]+1][a[1]+1][a[2]+1]);
}
fclose(fp);
}

int main()
{
int a[128][128][128];
function("abc.txt",a);
print("abc.txt",a);
return 0;
}

In my text file, I will be skipping the first row, then start reading from the 2nd row. My text files contains a set of integers.

Though its compiling, why cant I see the output?

Pls help.

Thanks!!  

Answer
1. Your program looks too complex, try to reduce the number of dimensions by changing the design, if possible.
2. Use a debugger to find from where the function and print calls return. I can see, function doesnt return integer through all paths - then how does it compile? Which compiler are you using?
3. You have to initialize the values in array a so that the program does not print garbage
4. For heaven's sake, use better names for functions and variables
5. If you're unable to debug a large program, try to find the minimum code that is cause of the problem (You can comment rest of the code while debugging). In test-driven programming, you should first write unit tests for your functionality. Only when the test fails, should you implement the functionality. Always think about unit testing the code before writing the code.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Amit Kumar

Expertise

I can answer Cplusplus language and library questions, including STL, ACE, Boost. I have a good background in Mathematics.

Experience

Programming in CPP for about 8 years. Industry experience of 4 years.

Education/Credentials
Bachelors and Masters in Computer Science from Indian Institute of Technology Delhi.

©2016 About.com. All rights reserved.