Please bear with me. This is my first post.

For some reason, I can only display the strings if I put the cout in the same loop. But since I have to separate addString() and displayAllStrings(), I can't do that. My displayAllStrings() keeps failing.

BUT when I write a separate display method, nothing is displayed.

Sometimes when I try editing that part of the code, I end up with 'subscript out of range' errors.

void Class::addString(vector<string>database, vector<string>newItem)
{
for(int r=0;r<9;r++)
    {
        database.push_back(newItem[r]);
        //cout<<"\n"<<r<<": "<<database[r]<<"\n"; //This can display
    }

void Class::displayAllStrings()
{
    for(int t=0; t<database.size(); t++)
    {

        cout<<"\n"<<t<<": "<<database[t]<<"\n";
    }
}

class Class
{
private:
    //last name, first name, street address, city, country, postal code, home phone number, mobile phone number, email address
    vector<string>database;
public:
    database();
    void displayAllStrings();
    void addString(vector<string> database,vector<string> newItem);
};

Edited 4 Years Ago by nullifyQQ

Well, I have to say: your code it's quite messy, and full of errors.

class Class

but yet you call the constructor as

database();

You have this as private

 vector<string>database;

yet you call

void addString(vector<string> database,vector<string> newItem);

with its own database vector<string> which will make this

database.push_back(newItem[r]);

locally, not actually adding something to your class, so it won't show you anything if you call displayAllStrings(), because your private member database will always be empty.

Here's an easy fix:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Class{
private:
    vector<string> database; //your private member
public:
    Class(){} //proper constructor for your class
    void displayAllStrings();
    void addString(vector<string> newItem); //removed the extra parameter
};

void Class::addString(vector<string>newItem){
    for(int r=0;r<(int)newItem.size();r++) { //looks up the size of the 2nd vector
        database.push_back(newItem[r]); //pushes items to your private vector<string>
    }
}

void Class::displayAllStrings(){
    for(int t=0; t<(int)database.size(); t++){
        cout<<t<<": "<<database[t]<<"\n"; //now it has items to print out.
    }
}

int main(){
    Class cls;
    vector<string> items;
    items.push_back("abc");
    items.push_back("bcd");
    items.push_back("def");
    items.push_back("efg");
    cls.addString(items);
    cls.displayAllStrings();
    return 0;
}

My output is as follows:

/*
 *0: abc
 *1: bcd
 *2: def
 *3: efg
 */

Edited 4 Years Ago by Lucaci Andrew

This article has been dead for over six months. Start a new discussion instead.