Saturday, May 9, 2009

C++ array to hold full name (first last) as a single string in array?

I need to store the full name, first and last name in an array as a single string, and its corresponding value in a parallel array. This means to store the full name in one location in the array. Using C++ and my compiler is Dev C++. I need help with this array primarily how to store the name as one unit and the value in a corresponding location in a parallel array. Here is my code so far:





#include%26lt;iostream%26gt;


#include%26lt;string%26gt;


#include%26lt;cstring%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;





using namespace std;








int main()





{





ifstream inFile;





char array1 [10] [50];


char array2 [10] [5];





inFile.open("celebs.txt");





int location = 0 ;





inFile %26gt;%26gt; array1[ location ] %26gt;%26gt; array2[ location ] ;





while ( inFile %26amp;%26amp; location %26lt; 50 )


{


location++;


inFile %26gt;%26gt; array1[ location ] %26gt;%26gt; array2[ location ] ;





}





this is the input file:





Donald Trump 5.1


Paris Hilton 2.98


Lindsey Lohan 3.65


Marion Jones 1.03


Paul McCartney 3.75


Snoop Dogg 1.65


Britney Spears 2.14


Sean Combs 1.07


Heather Mills 2.31


Michael Vick 4.67

C++ array to hold full name (first last) as a single string in array?
Since this is C++, you can take advantage of string methods. I recommend that you scan backward in your input for the last separating space and split the input at that point. Also, instead of two-dimensional char arrays, why not use array of strings? See below for my attempt:





#include%26lt;iostream%26gt;


#include%26lt;string%26gt;


#include%26lt;cstring%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;





using namespace std;





const int TotalRows = 10;





int main()





{





ifstream inFile;





string input_string, array1[TotalRows], array2[TotalRows];





inFile.open("celebs.txt");





int location = 0, linecount = 0 ;





while ( linecount %26lt; TotalRows )


{


getline(inFile, input_string);


location = input_string.rfind(" ");


array1[linecount] = str.substr(0, location);


array2[linecount] = str.substr(location+1);


linecount++;


}


inFile.close();





}

gladiolus

No comments:

Post a Comment