Input to a structure array not working?
Mar 23, 2014 at 2:39am UTC
I wrote this program to help me create a list of medical resources and their attributes, a task I have been performing repeatedly lately. I'm still fairly new to C++, so I thought to create a structure "Resource", and then an array of those structures "city[300]". My problem is that the input doesn't seem to be happening: the program runs, but when it prints to screen/writes to the file at the end, all the shows is:
Resource Type:
Name:
Address:
Phone:
Website:
for every resource that was input. All the fields are blank. I'm not sure what I'm doing wrong, please help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Resource
{
string typeID;
string name;
string address;
string phone;
string website;
string description;
}city[300];
int main()
{
bool next = true ;
int i = 0;
while (next)
{
cout << "\nType ID: " ;
getline(cin,city[i].typeID) ;
cout << "Name: " ;
getline(cin,city[i].name) ;
cout << "Address: " ;
getline(cin,city[i].address) ;
cout << "Phone: " ;
getline(cin,city[i].phone) ;
cout << "Website: " ;
getline(cin,city[i].website) ;
cout << "Description: " ;
getline(cin,city[i].description) ;
i++;
cout << "\nContinue? :" ;
cin >> next;
cout << endl << endl;
}
ofstream myfile("sanmateo.txt" );
for (int j=0;j<i;j++)
{
cout << "\nResource Type: " << city[i].typeID;
cout << "\nName: " << city[i].name;
cout << "\nAddress: " << city[i].address;
cout << "\nPhone: " << city[i].phone;
cout << "\nWebsite: " << city[i].website;
cout << "\n" << city[i].description;
cout << "\n\n" ;
myfile << "\nResource Type: " << city[i].typeID;
myfile << "\nName: " << city[i].name;
myfile << "\nAddress: " << city[i].address;
myfile << "\nPhone: " << city[i].phone;
myfile << "\nWebsite: " << city[i].website;
myfile << "\n" << city[i].description;
myfile << "\n\n" ;
}
myfile.close();
return 0;
}
Mar 23, 2014 at 7:32am UTC
at the bottom, you're using i as the index instead of what it should be : j.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
for (int j=0;j<i;j++)
{
cout << "\nResource Type: " << city[i].typeID;
cout << "\nName: " << city[i].name;
cout << "\nAddress: " << city[i].address;
cout << "\nPhone: " << city[i].phone;
cout << "\nWebsite: " << city[i].website;
cout << "\n" << city[i].description;
cout << "\n\n" ;
myfile << "\nResource Type: " << city[i].typeID;
myfile << "\nName: " << city[i].name;
myfile << "\nAddress: " << city[i].address;
myfile << "\nPhone: " << city[i].phone;
myfile << "\nWebsite: " << city[i].website;
myfile << "\n" << city[i].description;
myfile << "\n\n" ;
}
every reference to city[i] should be replaced with city[j], as the for loop is incrementing j, not i.
Hope that helps
Topic archived. No new replies allowed.