Read Input from Text file

I have a text file with some names in this format:
 
  "MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER"


How can store each name separated on a vector without the double quotes and the comas?
You can read each name in this format with the std::getline() function, reading until the next coma ( "NAME" );

Then you can erase for each string the quotes
1
2
3
4
string yourNameString;

yourNameString.erase(0);                          //erase first quote
yourNameString.erase(yourNameString.length());    //erase last quote 


And then do whatever you want with your vector.

Hope this helps.
Last edited on
Thank you!
Here is what I have.
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
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

int main() {
    std::vector<std::string> nameList;
   std::string line,name;
    std::ifstream nameFile ("22_names.txt");
    if (nameFile.is_open()) {
        std::getline(nameFile,line);
        std::stringstream ss (line);
        
        while(getline(ss,name,',')) {
            
            name.erase(0,1);
            name.erase(name.size()-1,name.size());
            nameList.push_back(name);
        }
    }
    
    else std::cout << "Unable to open" << std::endl;
    return 0;
}
You don't need erase() and (in this instance) the comma is irrelevant.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
   vector<string> nameList;
   string dummy, name;
   ifstream in( "22_names.txt" );
   while ( getline( in, dummy, '"' ) && getline( in, name, '"' ) ) nameList.push_back( name );

   for ( string s : nameList ) cout << s << '\n';
}


MARY
PATRICIA
LINDA
BARBARA
ELIZABETH
JENNIFER
Last edited on
Topic archived. No new replies allowed.