0

I just what to declare the array of struct and take input and show output through functions. I have structure name as studentType and want to make a array of this structure. i make for loop to run 3 time but it just run 2 times for input and then show the result and in output function show my first input in second itration

#include<iostream>
#include<conio.h>      
using namespace std;

void input();//prototype of input function
void print();
struct studentType{ 
        char firstName[10]; 
        char lastName[10]; 
        char courseGrade; 
        double GPA;
    };

int main()
{   
    studentType obj[3];
    input();
    print();

    getch();
    return 0;
}

void input() //taking input
{   
    studentType obj[3];

    for(int i=0; i<3 ; i++) 
    {
        cout<<"No."<<i<<" Enter Your First Name ?" ;    cin.getline(obj[i].firstName,10); cout<<"\n";

        cout<<"No."<<i<<" Enter Your last Name ?";      cin.getline(obj[i].lastName,10); cout<<"\n";

        cout<<"No."<<i<<" Enter Your Course Grade ?";   cin>>obj[i].courseGrade;         cout<<"\n";

        cout<<"No."<<i<<" Enter Your GPA ?";            cin>>obj[i].GPA;                 cout<<"\n";
    }
}

void print( )//showing results or printing
{   
    studentType obj[3];    //array obj its a struct type 
    for(int i=0; i<3 ; i++) 
    {
        cout<<"No."<<i<<" Your First Name"      <<obj[i].firstName<<endl;

        cout<<"No."<<i<<"last Name "            <<obj[i].lastName<<endl;

        cout<<"No."<<i<<"Your Course Grade "    <<obj[i].courseGrade<<endl;

        cout<<"No."<<i<<"Your GPA "             <<obj[i].GPA<<endl;

    }
}
  • Turn on all compiler warnings. They are very useful in those situations. In this particular case, you read uninitialized table `obj` in `void print()`. – Piotr Siupa Sep 10 '15 at 11:17
  • BTW, you probably should use `flush` before reading user input. More informations here: http://stackoverflow.com/questions/17370093/should-c-programmers-use-stdflush-frequently – Piotr Siupa Sep 10 '15 at 11:23
  • Giving things the same name does not make them the same thing. (I think [Ali Raza](https://www.linkedin.com/pub/dir/ali/raza) would confirm this.) – molbdnilo Sep 10 '15 at 12:25

1 Answers1

1

The immediate solution would be to comment out studentType obj[3]; from int main(), void input() and void print() and declare it as global variable. Otherwise each function works on a local copy of obj.

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
  • `obj` in `main` is also local. It should be moved outside the function or passed to `void input()` and `void print()`. – Piotr Siupa Sep 10 '15 at 11:13