0

I have written this code and I am supposed to read in a txt file and read every other line in the txt file to the string array bookTitle[ARRAY_SIZE] and the other every other line to bookAuthor[ARRAY_SIZE]. Here is my code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const int ARRAY_SIZE = 1000;
string bookTitle [ARRAY_SIZE];
string bookAuthor [ARRAY_SIZE];

int loadData(string pathname);
void showAll(int count);
//int showBooksByAuthor (int count, string name);
//int showBooksByTitle (int count, string title);


int main ()
{
    int number, numOfBooks;
    char reply;
    string bookTitles, authorName, backupFile;
    cout << "Welcome to Brigham's library database." << endl;
    cout << "Please enter the name of the backup file:";
    cin >> backupFile;
    numOfBooks = loadData (backupFile);
    if (numOfBooks == -1) {
        cout << endl;
    } else {
        cout << numOfBooks << " books loaded successfully." << endl;
    }
    cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All:";
    cin >> reply;

    do {
        switch (reply) {
            case 'a':
            case 'A':
                cout << "Author's name: ";
                cin >> authorName;
                showBooksByAuthor (numOfBooks, authorName);
                cout << endl;
                break;
            case 'q':
            case 'Q':
                cout << endl;
                break;
            case 's':
            case 'S':
                showAll(numOfBooks);
                break;
            case 't':
            case 'T':
                cout << "Book title: ";
                cin >> bookTitles;
                showBooksByTitle(numOfBooks, bookTitles);
                cout << endl;
                break;
            default:
                cout << "Invalid input" << endl;
                break;          
        }
    } while (reply != 'q' && reply != 'Q');

    while (1==1) {
        cin >> number;
        cout << bookTitle[number] << endl;
        cout << bookAuthor[number] << endl;
    }
}

int loadData (string pathname){
    int count = 0, noCount = -1;
    ifstream inputFile;
    string firstLine, secondLine;

    inputFile.open(pathname.c_str()); 

    if (!inputFile.is_open()) { //If the file does not open then print error message
        cout << "Unable to open input file." << endl;
        return noCount;
    }

    for (int i = 0; i <= ARRAY_SIZE; i++) {
        while (!inputFile.eof()) {
            getline(inputFile, firstLine);
            bookTitle[i] = firstLine;
            getline(inputFile, secondLine);
            bookAuthor[i] = secondLine;
            cout << bookTitle[i] << endl;
            cout << bookAuthor[i] << endl;  
            count++;
        }
    }

    return count;
}

void showAll (int count) {

    for (int j = 0; j <= count; j++) {
        cout << bookTitle[j] << endl;
        cout << bookAuthor[j] << endl;
    }
}

So I have the loadData function which I am pretty sure is my problem. When I have it print out each string[ith position] while running the loadData function it prints out each title and author just as it appears in the txt file. But then when I run the void showAll function which is supposed to be able to print the entire txt doc to the screen it doesn't work. Also just I checked to see if the strings were actually stored in memory and they were not. (After my do while loop I have a while loop that accepts input of type int and then prints the string array of the [input position]. This prints nothing. So what do I have to do to actually store each line to a different position in the string array(s)? Feel free to correct my code but it isn't pretty yet considering I still have two functions that I haven't done anything too. (Commented out).

7
  • 1
    First: for (int i = 0; i <= ARRAY_SIZE; i++) You are potentially going beyond the boundaries of your array here, and here: for (int j = 0; j <= count; j++) Second: while (!inputFile.eof()) Don't use eof. Commented Nov 28, 2015 at 18:30
  • 1
    Do not use inputFile.eof() a loop condition. Instead, check that input was successful after reading: the stream cannot know what you are going to read next. Commented Nov 28, 2015 at 18:33
  • Non-causal programs that did know the future would be really cool, but a expletive deleted to debug. Commented Nov 28, 2015 at 18:38
  • So, after all that, your problem statement is "it doesn't work"? Commented Nov 28, 2015 at 18:46
  • while (1==1) { er... Commented Nov 28, 2015 at 18:46

1 Answer 1

1

You main problem is that you try to read you data using two loops rather than just one! You want read until either input fails or the array is filled, i.e., something like this:

for (int i = 0;
     i < ARRAY_SIZE
     && std::getline(inputFile, bookTitle[i])
     && std::getline(inputFile, bookAuthor[i]); ++i) {
}

The problem with the original code is that it never changes the index i and always stores values into the cell with index 0. Since the input isn't checked after it is being read, the last loop iteration fails to read something and overwrites any earlier stored value with an empty value. Once reading of the stream fails the outer loop iterates over all indices but doesn't do anything as the check to the inner loop is always false.

Sign up to request clarification or add additional context in comments.

4 Comments

"you try to read you data using two loops rather than just one" Really? Where?
@LightnessRacesinOrbit: in the function loadData() (you want to look for a while-loop inside a for-loop).
@LightnessRacesinOrbit: indeed. Sometimes the issues are just to weird. It also took me some time before I spotted the actual problem as the loop didn't look as wrong as described...
Oh awesome thank you. That makes complete sense. Function works great now thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.