Hi,
I made a simple program that reads 3 names from a text file, each of which has a first name, middle name and surname. I think there would be a few ways to improve the program, although I'm not sure how to go about it. So I have a couple of questions, if anyone could help:
1. When I create the three vectors of strings, if I don't start off by putting something into them, the program crashes when it's run (lines 19-21). How come? Is there any way I can save code by not having to put something in them when I create them?
2. Is there any way of avoiding having to declare three separate vector<string> variables? Would it be possible to do this using just a vector of vectors? Or could you do it using one vector that's just 3 x 3 strings? Would a list of vectors be better?
Thanks guys.
In the code, the file "names.dat" is just a text file with the following in:
Arnold Adam Andrews
Brian Barry Buttfield
Colin Charles Coleman
Code:#include <iostream> #include <string> #include <vector> #include <fstream> #define FIRSTNAME 0 #define MIDNAME 1 #define SURNAME 2 using namespace std; ifstream file_in("names.dat"); int main() { char charname[99]; string string_from_file; int pos; int num_of_lines = 0; int typeofname = 0; vector<string> first_names; vector<string> middle_names; vector<string> last_names; first_names.push_back(string_from_file); middle_names.push_back(string_from_file); last_names.push_back(string_from_file); while(!file_in.eof()) // Get the names from the names.dat file. { file_in.getline(charname, 99); pos = 0; while (typeofname <= SURNAME) { string_from_file[string_from_file.size()] = NULL; string_from_file.erase(0, 99); while (((typeofname<=MIDNAME) && (charname[pos] != ' ')) || ((typeofname==SURNAME) && (charname[pos]))) { string_from_file += charname[pos]; pos++; } pos++; if (typeofname == FIRSTNAME) first_names.push_back(string_from_file); else if (typeofname == MIDNAME) middle_names.push_back(string_from_file); else if (typeofname == SURNAME) last_names.push_back(string_from_file); typeofname++; } num_of_lines++; typeofname = 0; } for (typeofname = 0; typeofname <= SURNAME; typeofname++) // Output the names by type. { pos = 0; while (pos <= num_of_lines) { if (typeofname == FIRSTNAME) cout << first_names[pos] << endl; else if (typeofname == MIDNAME) cout << middle_names[pos] << endl; else if (typeofname == SURNAME) cout << last_names[pos] << endl; pos++; } } }



LinkBack URL
About LinkBacks


