Hello
I have given a program in which i have to declare structure to store account ID, amount, user name and address. It inputs the number of account holders from the user and creat a dynamic array of structures to store the records of accounts. The program should declare two functions i.e. one for getting input from the user and other for showing records to the user.But my program is not fulfilling the requirements. It is not taking the inputs of name and address as it should. Got confused how to solve it.

#include<iostream.h>
#include<conio.h>
struct acc
{
int id;
double amount;
char name[50];
char add[150];
};
void input(acc *,int);
void output( acc *,int);
void main()
       {
	int n;
	cout<<"Enter total number of accounts:";
	cin>>n;
	acc *ptr;
	ptr=new acc[n];
	input(ptr,n);
	output(ptr,n);
	delete []ptr;

       getch();

       }
       void input(acc* x,int t)
       {
       int i;
       for(i=0;i<t;i++)
       {
       cout<<"Enter customer id:";
       cin>>x->id;
       cout<<"Enter the name : ";
       cin.get(x->name, 50);
       cout<<"Enter amount:";
       cin>>x->amount;
       cout<<"Enter the address";
       cin.get(x->add, 150);
       x++;
       }
       }
       void output(acc* y,int t)
       {
       for(int i=0;i<t;i++)
       {
       cout<<"Id :"<<y->id<<" name is : "<<y->name<<" amount: ";
       cout<<y->amount<<" address is : "<<y->add<<endl;
       y++;
       }
       }

Recommended Answers

All 2 Replies

Hello
... It is not taking the inputs of name and address as it should. Got confused how to solve it.

After the operator>>() , the input is left pointing at the end-of-line character. At the next call of get() , there is already input available (the end-of-line character), so it reads up to the end-of-line delimiter, which is zero characters.

A solution is to discard the rest of the line after you read the values, using cin.ignore() -- check the manual for how to use it.

cout << "Enter customer id:";
cin >> x->id;
cin.ignore(999, '\n');

Also, instead of <iostream.h> , you should be using <iostream> . iostream.h is an old version that is only kept for backwards compatibility with very old code.

There's another inconsistency when you are trying to dereference your struct members to write to them with cin. First, for multiple accounts you are not using the i value anywhere in your loop. So you need x to dereference your array pointer and then you can just use the dot operator, e.g. x[i].name to get the name element.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.