-
Arrays and Structs
Hello,
I've written a simple program that allows a person to enter some personal information about a person or people. You enter the name, address and are prompted to enter the number of bank accounts for each person and the individual account numbers. However when I enter information for two people with one bank account each the second person's account number comes out as garbage. Does anyone have any helpful suggestions??
#include <iostream>
using namespace std;
struct account{
int accountnum;
char accType;
float balance;
};
typedef struct account A;
struct Customer{
string name;
string address;
A * accArray;
};
typedef struct Customer Cu;
int main(){
int numCust, numAccounts;
cout << "Enter number of customers"<<endl;
cin >>numCust;
cin.ignore();
Cu * cArray = new Cu[numCust];
for ( int i=0; i < numCust; i++)
{
cout << "Enter name"<<endl;
getline(cin, cArray[i].name);
cout <<"Enter address"<<endl;
getline(cin, cArray[i].address);
cout <<"Enter number of accounts"<<endl;
cin >> numAccounts;
cArray[i].accArray = new A[numAccounts];
for ( int j=0; j < numAccounts; j++)
{
cout <<"enter account number for "<< j+1<<endl;
cin >> cArray[i].accArray[j].accountnum;
}
cin.ignore();
}
cout << "\nName \t\t Address\t Account Number"<<endl;
for (int i=0; i< numCust; i++)
{
cout <<cArray[i].name<<"\t\t"<<cArray[i].address<<"\t"<<cArray[i].accArray[i].accountnum<<endl;
}
system ("Pause");
return 0;
}
-
Its your print loop.
for i = 0....
second time through, your print account[1] (the valid one is account[0]) because you indexed everything off i but accounts needs a second index just like you had when you put them in.
-
You declare a variable i in for loop scope and use it in another for loop score. Wrong.
-
 Originally Posted by Peter_APIIT
You declare a variable i in for loop scope and use it in another for loop score. Wrong.
Each for loop has its own scope, so the variable i declared in one loop doesn't conflict with another i declared in the second loop.
Danny Kalev
Similar Threads
-
Replies: 17
Last Post: 10-01-2003, 12:00 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks