Here is the names.dat file: Collins, Bill Smith, Bart Michalski, Joe Griffin, Ji
ID: 3620980 • Letter: H
Question
Here is the names.dat file:Collins, Bill
Smith, Bart
Michalski, Joe
Griffin, Jim
Sanchez, Manny
Rubin, Sarah
Taylor, Tyrone
Johnson, Jill
Allison, Jeff
Moreno, Juan
Wolfe, Bill
Whitman, Jean
Moretti, Bella
Wu, Hong
Patel, Renee
Harrison, Rose
Smith, Cathy
Conroy, Pat
Kelly, Sean
Holland, Beth
I have to read in those names into a vector of strings. Here's what I got so far:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream inFile;
vector<string> names(20);
inFile.open("names.dat");
for (int i = 0; i < 20; i++)
{
inFile >> names[i];
cout << names[i] << endl;
}
inFile.close();
return 0;
}
The problem is that I can't get it to read in the entire name. It's counting each word in a person's name as a name. How do I get it to read in all of the names?
Explanation / Answer
C++ reads the spaces in the vector as a separator between 2 elements in the vector.
Let's look at the first name you want to read in. Collins, Bill. C++ would read this as 2 different names because of the space and therefore your for loop would stop half way down the list of names.
Note: C++ will read Collins_Bill as 1 name instead of 2