hey everyone. been trying to figure out this assignment but cant quit get it.
what i need to do is open a given txt file and read it its contents and place them into a vector.
the practice file is this:
9 John 3 Jane 7 Tom 2 Sam
6 Tom 1 Nicole 5 Tom
4 Jane 8 Ben
i need to place the names in the file into a vector in the order of the number in front of them. so it should look like this when i cout the vector contents:
nicole
sam
jane
jane
tom
tom
tom
ben
john
the code that i have written so far does this:
9
John
3
Jane
7
Tom
2
Sam
6
Tom
1
Nicole
5
Tom
4
Jane
8
Ben
i have counted through the vector and found that there are 9 names in the file. then i created a new vector called "names" that has a size of 9. my idea is to count through the original vector "v" and check at each position of v[i] for the number 1 (which i assigned to the character x). so if v[i] == x then i want the code to take the string after that character, v[i+1] and push that string into the new vector "names" using names.push_back().
the code in bold is where im having trouble. i believe it is because the vector v is in strings and i need to convert it to integers before i can compare my first condition of x < v.size() but i dont know how to do this.
so please help me out if you can understand what im trying to do. haha.
this is my code:
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 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <string>
#include <cctype>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <fstream>
using namespace std;
void fill_vector ( vector<string> &v );
void print_vector ( vector<string> names );
int count_names ( vector<string> v );
int main()
{
vector<string> v;
string s;
fill_vector(v);
int num_names;
num_names = count_names(v)/2;
cout << "number of names " << num_names << endl;
vector<string> names[num_names];
int x = 1;
while ( x < v.size() )
{
for ( int i = 0; i < v.size(); i++ )
{
if ( v[i] == x )
{
names.push_back ( v[i + 1] );
break;
}
}
x++;
}
print_vector(v);
return 0;
}
void fill_vector ( vector<string> &v )
{
string s;
ifstream fin;
string input = "toy_names.txt";
fin.open ( input.c_str() );
fin >> s;
while ( !fin.eof() )
{
v.push_back ( s );
fin >> s;
}
}
void print_vector ( vector<string> names )
{
for ( int i = 0; i < names.size(); i++ )
cout << names[i] << endl;
}
int count_names ( vector<string> v )
{
int counter = 0;
for ( int i = 0; i < v.size(); i++ )
{
counter++;
}
return counter;
}
|