• Advertisement
Sign in to follow this  

vector<string> inside class not working

This topic is 1648 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ello. The strings in this vector say null everytime i run it.

entity.h


#include <vector>
#include <string>

using namespace std;

class Hero
{
public:
		vector<string> storage;
		void addStorageItem(string);
};

entity.cpp

#include "entity.h"

Hero::Hero()
{
}

Hero::~Hero()
{
}

void Hero::addStorageItem(string x)
{
	storage.push_back(x);
}


main()

#include <stdio.h>
#include <conio.h>
#include "entity.h"

int main()
{
	Hero myHero = Hero();
	
	myHero.addStorageItem("Hi");
	myHero.addStorageItem("How are you");

	for(int i = 0; i < myHero.storage.size(); i++)
	{
		printf("item Name: %s\n", myHero.storage[i]);
	}

	getch();
	return 0;
}


Share this post


Link to post
Share on other sites
Advertisement

%s expects a pointer to a null terminated char string, not a std::string object.

 

Change to myHero.storage.c_str() and it should work.

Share this post


Link to post
Share on other sites

The main issue:
You're passing a std::string to printf, and trying to display it with a %s. printf is a C function (not C++), so it expects to receive strings of type "char*", not "std::string".
 
The correct way to pass a C++ string to C's printf is:

printf("item Name: %s\n", myHero.storage[i].c_str());

or in C++:

cout << "item name: " << myHero.storage[i] << endl;

 
Other issues:
You have using namespace std; in a header file. This should only ever go in cpp files, not h files.

(You can google "using namespace in headers" to find discussion on that point, e.g. http://stackoverflow.com/questions/5849457/using-namespace-in-c-headers)
 
addStorageItem is passing std::strings by value. This creates extra temporary copies of them. You should be passing them by const-reference:
void Hero::addStorageItem(const string& x):
 
Hero has an empty constructor and destructor. If they don't do anything, you can just not write them.
In your header file, Hero doesn't have a constructor or destructor -- so the fact that you have them in your cpp file means this code shouldn't compile at the moment ;P
 
Hero myHero = Hero(); is redundant. This code says to construct a temporary unnamed Hero object, then to copy construct myHero using that temporary.
You can just write: Hero myHero;

Edited by Hodgman

Share this post


Link to post
Share on other sites

printf's "%s" is for c-style strings (an array of char that ends with zero), not c++ strings.

 

try:

printf("item Name: %s\n", myHero.storage[i].c_str());

 

or in c++ style yet:

cout << "item Name: " << myHero.storage[i] << '\n';

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement