You are here:

C++/Faulty Programme !!??

Advertisement


Question
Sir, thank you for your kind consideration of my problem. You were not able to answer my question previously as you did not get access to the source code. Therefore, now I provide it here, (below).

Source Code Begins Here:
//Including Header Files
#include <fstream.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
#include <process.h>
#include <ctype.h>
#include <stdlib.h>
#include <dos.h>
//Header files Included


//Defining global variables
long ct=0;
//Definition of global variables - over


//Defining Class
class info
{
public:
long pos;
char name[30];
long rno;
int mark[2][3];
int total[2], gtotal;
float percentile;

void calc(void);

public:

info()
{
int i,j;
strcpy(name,"!");
rno=-1;
for (i=0; i<2; i++)
  {
  for (j=0; j<3; j++)
     {
     mark[i][j]=-1;
     }
  }
total[0]=total[1]=gtotal=0;
pos=1;
percentile=100;
}

void enter_data(int);
long get_rno(void);
};
//Class Defined


//Declaring global functions
void show(void);
void student(void);
void prof(void);
void enter_new(void);
void calc_per(void);
void del(void);
void modify(void);
void count(void);
void writefile(char [], info);
void see_result(long);
int check_rno(long);
//Decleration of global functions - over


//Defining Class (info) functions

//For Calculating total per paper and grand total
void info::calc()
{
int i,j;
for (i=0; i<2; i++)
  {
  for (j=0; j<3; j++)
     {
     total[i]+=mark[i][j];
     }
  }
gtotal=total[0]+total[1];
}
//Calculation of total per paper and grand total over

//To enter data and calculate all totals
void info::enter_data(int a=1)
{
int i,j,k;

entr_rno:;
clrscr();
cout<<"Enter Roll Number :";
cin>>rno;
//Constranting
if (rno<0)
  {
  cout<<"\n\nPlease provide Positive Roll Numbers!!!\n\nPress Any Key to Re-Enter :";
  getch();
  goto entr_rno;
  }

if (a==1)
  {
  k=check_rno(rno);
  }
else
  {
  k=0;
  }

if (k)
  {
  cout<<"\n\n!!!Roll Number already present!!! Please provide different Roll Number. \nPress any key to enter again :";
  getch();
  goto entr_rno;
  }
//Costranting Complete

cout<<"Enter Name :";
gets(name);
for (i=0; i<2; i++)
  {
  cout<<"\nEnter Marks of Three Subjects in Paper "<<(i+1)<<"\n";
  for (j=0; j<3; j++)
     {
     entr_mrk:;
     cout<<"\nSubject"<<(j+1)<<" :";
     cin>>mark[i][j];
     if (mark[i][j]>100)
        {
        cout<<"\n\nPlease enter a number less than 100.\nPress Enter to Re-Enter :";
        getch();
        clrscr();
        goto entr_mrk;
        }

     }
  }

calc();
}
//Data entered and all totals calculated

//Returning Roll No (of 'this') - Remember roll no is our Unique ID
long info::get_rno()
{
return rno;
}
//Roll No returned

//Defining of class (info) functions - over


//Defining global Functions

//Showing data from file
void show()
{
::ct=0;
count();
info B;
ifstream A;
A.open("Tutorial.txt");

int i,j;
long l;

l=0;
while (l<::ct)
  {
  A.read((char*) &B, sizeof(B));
  cout<<"\n\n\nName :"<<B.name<<"\nRoll Number :"<<B.rno;
  for (i=0; i<2; i++)
     {
     cout<<"\n\nMarks of Paper "<<(i+1)<<"\n";
     for (j=0; j<3; j++)
        {
        cout<<"\n Subject "<<(j+1)<<" = "<<B.mark[i][j];
        }
     }
  cout<<"\n\nPosition = "<<B.pos;
  cout<<"\n\n\t\tPERCENTILE = "<<B.percentile;
  l++;
  if (l<::ct)
     {
     cout<<"\n\nPress Any Key to see Next :";
     getch();
     }
  }
A.close();
}
//Showing data from file - Completed

//Student Menu
void student()
{
clrscr();
char ans=0, comp[201]={"I LOVE ***** TUTORIAL"};
long rno=-1;
ofstream A;          //decreaing here as inside switch it gives error

choice3:;
clrscr();
cout<<"WELCOME our dearest student!!!\n\n";
cout<<"\nWhat do you want to do: :-\n\t1.See Test Results\n\t2.Submit a Complaint/Message\n\t3.Exit\n\nAns :";
ans=getch();

switch (ans)
  {
  case '1'   :   cout<<"\n\nEnter your Roll Number :";
         cin>>rno;
         see_result(rno);
         goto choice3;
  case '2'   :   cout<<"\n\nEnter your Roll Number :";
         cin>>rno;
         cout<<"\n\nEnter you Complaint/Message (in less than 200 charecters) :-\n";
         gets(comp);
         A.open("complaint.txt", ios::app);
         A<<endl<<rno<<endl<<comp<<endl;
         A.close();
         goto choice3;
  case '3'   :   cout<<"\n\nPress the 'X' on the top right corener of this window to exit the Portal!";
         exit(0);
  default   :   cout<<"\n\nWRONG CHOICE! Press any key to return and try again :";
         getch();
         goto choice3;
  }

}
//Student Menu - over

//Professional Menu
void prof()
{
clrscr();
char ans,pass[10];
cout<<"Enter Password :";
gets(pass);
if (strcmp(pass,"ani"))
   {
   cout<<"\n\nABORTING !!!!!!!\n\t\tWRONG PASSWORD!";
   delay(5000);
   exit(0);
   }
choice2:;
clrscr();
cout<<"\n\nWhat do you want to do? :-\n\t1.Enter New Record\n\t2.Delete Record\n\t3.Modify Record\n\t4.See all Records\n\t5.Exit\n\nAns :";
ans=getch();          //Automatic truncation of Decimal

switch (ans)
  {
  case '1'   :   enter_new();
         goto choice2;
  case '2'   :   del();
         goto choice2;
  case '3'   :   modify();
         goto choice2;
  case '4'   :   clrscr();
         show();
         cout<<"\n\nPress Any Key to Return :";
         getch();
         goto choice2;
  case '5'   :  cout<<"\n\nPress the 'X' on the top right corener of this window to exit the Portal!";
         exit(0);
  default   :  cout<<"\n\nWRONG CHOICE! Press any key to return and try again :";
         getch();
         goto choice2;
  }

}
//Professional Menu - over

//To enter new record(s)
void enter_new()
{
clrscr();
info I;
I.enter_data();          //Enter data and calculate grand total
writefile("Tutorial.txt",I);  //Write in file
cout<<"\n\nData Entry Complete!!! Press Any Key to continue :";
getch();
::ct=0;
count();
calc_per();
}
//Entering of new data - over

//Calculation of Position and Percentile for ALL RECORD(S)
void calc_per()
{
::ct=0;
count();

long l1=0, l2=0;
info I,J;

//Making a Copy of the File
ifstream Z;
ofstream Y;
Z.open("Tutorial.txt");
Y.open("Temp.txt");

while (l1<::ct)
  {
  Z.read((char *) &I, sizeof(I));
  Y.write((char *) &I, sizeof(I));
  l1++;
  }

Z.close();
Y.close();
//Copy made!
ifstream A,B;
A.open("Tutorial.txt");
B.open("Temp.txt");
ofstream C;
C.open("Temp2.txt");

l1=0;
while (l1<ct)
  {
  A.read((char*) &I, sizeof(I));
  l2=0;
  B.seekg(0);

  I.pos=1;
  while (l2<ct)
     {
     B.read((char*) &J, sizeof(J));

     if (I.gtotal<J.gtotal)
        {
        I.pos++;
        }
     l2++;
     }
  I.percentile=ct-I.pos;
  I.percentile=(I.percentile/ct)*100;
  C.write((char*) &I, sizeof(I));
  l1++;
  }

A.close();
B.close();
C.close();

remove("Tutorial.txt");
remove("Temp.txt");
rename("Temp2.txt","Tutorial.txt");
}
//Calculation of Position and Percentile for ALL RECORD(S) - over

//Deletion of record(s)
void del()
{
long rno, ct2=0;

info I;

clrscr();
cout<<"Enter Roll Number to delete : ";
cin>>rno;

ifstream A;
ofstream B;
A.open("Tutorial.txt");
B.open("Temp.txt");

long l=0;
while (l<::ct)
  {
  A.read((char *) &I, sizeof(I));
  if(I.get_rno()!=rno)
     {
     B.write((char *) &I, sizeof(I));
     }
  else
     {
     ct2++;
     }
  l++;
  }

A.close();
B.close();

remove("Tutorial.txt");
rename("Temp.txt","Tutorial.txt");

::ct=0;
count();
calc_per();

if (ct2==0)         //i.e. record not found
  {
  cout<<"\n\nRecord Not Found!!! Press any key to try again :";
  getch();
  return;
  }

cout<<"\n\nRequested Record DELETED!!!";
cout<<"\n\nPress Any Key to Return :";
getch();
}
//Record(s) deletion - over

//Modification of Record(s)
void modify()
{
clrscr();

info I,J;
char ans;
int ct=0;

I.enter_data(0);

ifstream A;
ofstream B;
A.open("Tutorial.txt");
B.open("Temp.txt");

long l=0;
while (l<::ct)
  {
  A.read((char *) &J, sizeof(J));
  if (I.get_rno()==J.get_rno() && ct==0)
     {
     B.write((char *) &I, sizeof(I));
     ct++;
     }
  else
     {
     B.write((char *) &J, sizeof(J));
     }
  l++;
  }

A.close();
B.close();

remove("Tutorial.txt");
rename("Temp.txt","Tutorial.txt");


if (ct==0)
  {
  que:
  cout<<"\n\n\t!!!Roll Number Not Found!\n\tDo you want to add as a new entry? (Y/N):";
  cin>>ans;
  switch (ans)
     {
     case    'Y'   :
     case    'y'   :   writefile("Tutorial.txt",I);
         cout<<"Data Entry Complete!!! Press Any Key to continue :";
         getch();
         ::ct=0;
         count();
         calc_per();
         break;
     case   'N'   :
     case   'n'   :   break;
     default      :   cout<<"\n\nWRONG CHOICE! Press any key to return and try again :";
         getch();
         goto que;
     }
  }

::ct=0;
count();
calc_per();

cout<<"\n\nData Modification Complete!!!";
cout<<"\n\nPress Any Key to Return :";
getch();
}
//Modification of records - over

//To count the number of Record(s) present in file
void count()
{
info I;
ifstream A;
A.open("Tutorial.txt");
long prev_rno=-1;

A.seekg(0);
while (!A.eof())
  {
  A.read((char*) &I, sizeof(I));

  if (I.get_rno()!=-1 && I.get_rno()!=prev_rno)
     {
     ::ct++;
     }
  prev_rno=I.get_rno();
  }
A.close();
}
//Counting of  number of Record(s) present in file - over

//Writing a (specified) variable into (specified) file
void writefile(char B[], info I)
  {
  ofstream A;
  A.open(B, ios::app);
  A.write((char *)&I, sizeof(I));

  A.close();
  }
//Writing of a (specified) variable into (specified) file - over

//To see result of a specific student
void see_result(long rno)
{
::ct=0;
count();

ifstream A;
A.open("Tutorial.txt");
info I;
int i,j;

long l=0;
while (l<::ct)
  {
  A.read((char*) &I, sizeof(I));

  if (I.get_rno()==rno)
     {
     cout<<"\n\n\nName :"<<I.name<<"\nRoll Number :"<<I.rno;
     for (i=0; i<2; i++)
        {
        cout<<"\n\nMarks of Paper "<<(i+1)<<"\n";
        for (j=0; j<3; j++)
         {
         cout<<"\n Subject "<<(j+1)<<" = "<<I.mark[i][j];
         }
        }
     cout<<"\n\nPosition = "<<I.pos;
     cout<<"\n\n\t\tPERCENTILE = "<<I.percentile;
     cout<<"\n\nPress Any Key to Return :";
     getch();
     A.close();
     return;
     }
  l++;
  }

cout<<"\n\nRoll Number not Found\nPress Any Key to Return and Re-Enter:";
getch();
A.close();
return;
}
//To see result of a specific student - over


//To check if roll number is present
int check_rno(long a)
{
info I;
ifstream A;
A.open("Tutorial.txt");
while (!A.eof())
  {
  A.read((char*) &I, sizeof(I));
  if (I.get_rno()==a)
     {
     return(1);
     }
  }
return(0);
}
//To check if roll number is present



//Declaration and Definition of 'Main()'
void main()
{
ofstream temp;
temp.open("Tutorial.txt", ios::noreplace);
temp.close();

char ans;
choice1:;
clrscr();
cout<<"Welcome to Electronic Portal of '***** Tutorial'\n\n";
cout<<"Are you a :-\n\t1.Tutorial Student\n\t2.Tutorial Professional\n\nAns :";
ans=getch();

switch (ans)
  {
  case '1':   student();
         break;
  case '2':   prof();
         break;
  default:      cout<<"\n\nWRONG CHOICE! Press any key to return and try again :";
         getch();
         goto choice1;
  }


}
//Declaration and Definition of 'Main()' - over
Source Code Ends Here

Please run the programme in C++, and :-

Go to professional menu (Press 2)

password is "ani"

go to enter new record (Press 1)

Feed in the following information:-
Roll No. : 999
Name : A
Marks   :99
       99
       99
      :99
       99
       99

Again, go to enter new record (Press 1)

Feed in the following Information:-
Roll No. : 2
Name : B
Marks   :25
       26
       27
      :28
       29
       30

Now go to 'see all result' (Press 4)

The information of the second child comes all wrong; muddled up with the previous record's marks!

Please be kind enough to explain me the reason for this error/bug (ASAP).

Thank You!

Answer
Hi, Anirudh.

OK, so, I was correct about your issue.  Input in C and C++ is a fun little beast to tackle.  There are numerous situations where some bit of data has been left in the buffer and it's up to you to clear it out.  That's the situation you're running into here.  When you try to get the string, the buffer still contains the newline character ('\n') from the previous input (since the previous input was only looking for numbers).  This is what you must clear out before you can enter a name.  A simple loop will accomplish this:

   char ch;
   while ( std::cin.get ( ch ) && ch != '\n' );

Just place that immediately before the gets call and you will be fine.

There are, however, other issues I would like to discuss in your program.

You are using the goto call all over the place.  This is, with rare exception, bad.  There is almost always a better way.  Sometimes the better way is not immediately obvious and requires a particular programming paradigm, but it is there.  Unless you are absolutely certain of your reasoning, and would defend it to the death, you should not use goto.

In this particular program, your use of goto would be better suited to for or while loops.  Take your main loop, for example:

   void main()
   {
       ofstream temp;
       temp.open("Tutorial.txt", ios::out);
       temp.close();

       char ans;
   choice1:;
       cout<<"Welcome to Electronic Portal of '***** Tutorial'\n\n";
       cout<<"Are you a :-\n\t1.Tutorial Student\n\t2.Tutorial Professional\n\nAns :";
       ans=getch();

       switch (ans)
       {
       case '1': student();
         break;
       case '2': prof();
         break;
       default: cout<<"\n\nWRONG CHOICE! Press any key to return and try again :";
         getch();
         goto choice1;
       }
   }

Here, and in several other similar sections of code, a do/while loop is far more appropriate:

   void main()
   {
       ofstream temp;
       temp.open("Tutorial.txt", ios::out);
       temp.close();

       char ans;
       do
       {
         cout<<"Welcome to Electronic Portal of '***** Tutorial'\n\n";
         cout<<"Are you a :-\n\t1.Tutorial Student\n\t2.Tutorial Professional\n\nAns :";
         ans=getch();

         switch (ans)
         {
         case '1': student();
         break;
         case '2': prof();
         break;
         default: cout<<"\n\nWRONG CHOICE! Press any key to return and try again :";
         getch();
         }
       } while (ans != '1' && ans != '2');
   }

OK, I've gotten off on a bit of a tangent, but hopefully this should have answered your question, at least. :)  If you need any further assistance, please don't hesitate to ask.  I'm here to help.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C++ code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2016 About.com. All rights reserved.