i have an assignment to read city names followed by populations into a vector of structure. the structure is city_data, and consists of a 25 char string and an int. i pass the vector by reference to the getcity function, where the file input is performed.
the file appears to be reading correctly, but my char string stops recieving values after the 10th character read from each line.
upon exiting the function and returning to main, i attempt to output my vector again. this time, it doesn't give me anything useful! here's the sample output from the main function:
================================
here is the output from the city variable:
≡¡║½½½½½½½½
================================
and that is supposed to run through the entire string.
i don't think i should be having this much trouble getting this input!
oh, i also attached the data file if anybody perchance compiles this and wants to help
Code:#include <iostream> #include <vector> #include <fstream> #include <cassert> #include <cctype> using namespace std; struct city_data { char name[25]; int population; }; int count_lines(); void getcity(vector<city_data>& data); void zero_vector(vector<city_data>& data, int lines); int main() { int initialize=0; int size=0; initialize=count_lines()/2; vector<city_data> city(initialize); size=city.size(); zero_vector(city, initialize); getcity(city); //debug***************************** cout<<"here is the output from the city variable:" <<endl; for (int k=0;k<initialize;k++); { for (int m=0;m<25;m++) { cout<<city[k].name[m]; } cout<<endl; cout<<city[k].population <<endl; } //debug***************************** system("PAUSE"); return 0; } void getcity(vector<city_data>& data) { ifstream infile; infile.open("lab3.txt"); assert(infile); char tempchar; for (int i=0; !infile.eof();i++) { tempchar=0; infile.peek(); /*this is the for loop that seems to be giving me trouble. it gets chars up to the 10th time, but exits the loop automatically afterwards.*/ for (int j=0;(infile.peek()!='\n')&&(j<25); j++) { infile.get(tempchar); if (tempchar!='\n') { data[i].name[j]=tempchar; cout<<tempchar; } } cout<<endl; infile>>ws; infile>>data[i].population; infile>>ws; for (int n=0;n<25&&n!='\n';n++) { cout<<data[i].name[n]; } cout<<endl; cout<<data[i].population <<endl; } infile.close(); } int count_lines() { ifstream infile; infile.open("lab3.txt"); assert(infile); char temp=0; int number=0; for (int i=0;!infile.eof(); i++) { if (!infile.eof()) { infile.get(temp); if(temp=='\n') { number++; } } } infile.close(); return number; } void zero_vector(vector<city_data>& data, int lines) { for (int i=0;i<lines;i++) { for (int j=0;j<25;j++) { data[i].name[j]='0'; } data[i].population=0; } }