1

I have a text file containing several book names and their correlating ISBN numbers in the format shown below, names separated by a tab space.

Neuromancer    345404475
DUNE    441172717
Ringworld    345020464
The Expanse    441569595
Do Androids Dream of Electric Sheep?    316129089

I use extraction operator overloading for this data and then I push back this information into a BookData class vector and subsequently use an iterator to loop through and then output this data.

Everything works as planned with one exception: book names that contain whitespace, "The Expanse", do not show up. I understand now after some reading that extraction operators stop at any whitespace. "The" is read as the name and then it tries to read "Expanse" as the isbn number which causes it to stop reading.

My question: Is there any possible way to add parameters to the extraction operator to allow it to ignore single spaces from the text file, but still stop at tabs or multiple spaces so that books names containing whitespace can be used?

#include <iostream>
#include <conio.h>
#include <string>
#include <vector>
#include "BookData.h"
#include <fstream>
using namespace std;

int main() {
    string line;
    string names;
    int isbns;

    ifstream fileObj1;
    fileObj1.open("bookNameAndIsbn.txt");       
    vector <BookData> bookDataVec;

    fileObj1 >> names >> isbns;
    while (getline(fileObj1, line)) {
        bookDataVec.push_back(BookData(names, isbns));
        fileObj1 >> names >> isbns; 
    }

    vector<BookData>::iterator it;
    for (it = bookDataVec.begin(); it != bookDataVec.end(); it++) {
    static int i = 0;
    cout << bookDataVec[i].getName() << " " << bookDataVec[i].getIsbn() << endl;
    i++;
    }
    _getch();
    return 0;
}

(header for BookData class below)

#pragma once
#include <string>    
using namespace std;

class BookData
{
public:
    BookData(string bookName, int bookIsbn);
    string getName();
    int getIsbn();

private:
    string _bookName;
    int _bookIsbn;
};    

(cpp for BookData class below)

#include "BookData.h"
#include <string>
using namespace std;

BookData::BookData(string bookName, int bookIsbn)
{
    _bookName = bookName;
    _bookIsbn = bookIsbn;
}

string BookData::getName() {
    return _bookName;
}

int BookData::getIsbn() {
    return _bookIsbn;
}
4

0 回答 0