Vector of pointers

closed account (DEUX92yv)
I have a class, User, with a member string name;. In main(), I declare vector<User*> userList; and add a few pointers to User objects with
1
2
userList.push_back(new User);
userList[userList.size() - 1]->name = "a name";

Later, I want to print out each User's name, so I tried cout << userList[i]->name;, and nothing prints. I know (or at least I think) that the dot operator is not appropriate here. What is the correct way to access these members?
Last edited on
This statement

userList[userList.size()]->name = "a name";

is invalid because valid indexes are in the range [0, userList.size() - 1]

You could change this stattement to

userList.back()->name = "a name";
Last edited on
closed account (DEUX92yv)
Sorry! I forgot about that. I got a seg fault error and in my actual file I'd already fixed it using .back(), but forgot to put that in this forum. I still don't get anything when I try to print though.
Last edited on
I do not see any problem to find the error. Simply include everywhere in the code test output of name. For example

userList.push_back( new User );
userList.back()>name = "a name";
std::cout << userList.back()->name << std::endl;

I think that the reason is somewhere either in the definition of the copy assignment operator of class User or in some operations with the list.

Last edited on
closed account (DEUX92yv)
I've discovered that the problem is when I get the name as input. I use getline(cin, tempdata), where tempdata is a name followed by an age. The reason I have to use getline is that if tempdata is "done", I break out of the function, so I cannot use cin >> tempname >> tempage.

After that, I use a for loop to find out how many characters are in tempdata before the space, and copy the name into tempname. I know this is where my problem is now, but can't figure out what it is.
1
2
3
4
5
6
7
8
9
10
for (int i = 0; i < tempdata.length(); i++) {
	if (tempdata[i] == ' ') {		// Check name's length
		namelength = i;
		break;
	}
	else {
		tempname[i] = tempdata[i];		// Copy name
	}
}
cout << tempname;

The last cout statement does nothing.
Last edited on
closed account (DEUX92yv)
I found a working solution to taking in input and splitting it into strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <sstream>
#include <iostream>
#include <vector>

int main() {
    std::vector<std::string> strings;
    std::istringstream f("denmark;sweden;india;us");
    std::string s;    
    while (std::getline(f, s, ';')) {
        std::cout << s << std::endl;
        strings.push_back(s);
    }
}
Topic archived. No new replies allowed.