Getting garbage from vector output

Hi,

So I'm having a problem getting information from a vector I've created.

The vector is composed of a class I've called "person". When I try to get the first name of the person I usually get garbage text i.e some weird text I can't type.

I believe the problem is the transfer of the name between the classes, but I'm not sure.

The flow of the program goes as such:

Choice getting (in main.cpp)
1
2
3
4
else if (decision == 3)
{
   MyDecisionProcessor.FIND();
}


Getting the ID of the person (in decisionProcessor.cpp)
1
2
3
4
5
6
printf("Insert the member ID of the person you want to find : ");
fgets(choice, MAX_INPUT, stdin);

sscanf(choice, "%d", &MemberID);

MyDatabase.find(MemberID);



Here is the outputting/finding function (in database.h)

1
2
3
4
5
6
7
8
9
vector<Person>::iterator i;

for (i = DBase.begin(); i != DBase.end(); ++i)
{
	if (i->getID() == ID)
	{
		printf("The name is %s", i->getFirst());
	}
}


Now, I've stepped through and I get into the IF of the above loop, so I know that
 
if (i->getID() == ID)

does function as it should. "The name is " also prints out, but I get 3 weird characters even if the name was longer.

and here is the get name function (in person.h)
1
2
3
4
string getFirst (void)
{
   return FirstName;
}



ANY help is appreciated, if you need to see any more of the code just ask.
C stdio and C++ strings do not mix well.

printf("The name is %s", i->getFirst());

This is actually invalid. %s expects a pointer to a char array and you are giving it a std::string. Since printf isn't typesafe, you don't get any error, you just get weird results.

You have to do one of the following (instead in the order in which I recommend them):

1) Forget about C stdio and use C++ iostream

or

2) convert your std::strings to char arrays before giving them to C stdio (with the c_str function)

or

3) forget about C++ string and use char arrays.


Example of #1:

1
2
//printf("The name is %s", i->getFirst());  // bad
cout << "The name is " << i->getFirst(); // good 


Example of #2:
1
2
//printf("The name is %s", i->getFirst());  // bad
printf("The name is %s", i->getFirst().c_str());  // good 


Doing an example of #3 would be considerably more work, as you'd have to rewrite a bunch of stuff (I don't recommend #3 anyway, I only mentioned it for completeness).

Really, you should stick to iostream (cin, cout) and forget about printf/scanf.


Note: sscanf in particular is very bad if you're trying to use it with a std::string. I can't tell whether or not you're doing that here, but if you are you really need to fix that or you might experience very weird crashes later. (also note the c_str() approach will not work with sscanf, so don't try it)
Last edited on
Thank you soo much! It works perfectly now!
Topic archived. No new replies allowed.