4

I'm trying to use a variable argument list to make NPCs in my text-based RPG talk easily. There's so many errors I'm not even bothering to post them - I gather I'm using this so wrong you won't need the output. If you do, of course I'll post it.

Here's the two files you'll need:

//Globals.h

#ifndef _GLOBALS_
#define _GLOBALS_

//global variables

#include "Library.h"
//prototypes
bool Poglathon();
void NPCTalk(string speaker,string text,...);

//functions
void NPCTalk(string speaker,string text,...){
    va_list list;
    va_start(list,text);
    while(true){
        string t = va_arg(list,string);
        if (t.compare("")==0)
            break;
        cout << speaker << ": "<< t << endl << endl;
        system("PAUSE");
    }
}

#endif

And the other one:

//Library.h

#ifndef _LIBRARY_H_
#define _LIBRARY_H_

#include <iostream>
using namespace std;

#include "Globals.h"
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdarg>

#endif
3
  • If you want to use std::string you'll have to include <string>. Commented Mar 20, 2011 at 12:47
  • 2
    It's not a good idea to try to pass non-POD types (such as std::string) to variadic functions. The results will be non-portable, and problems it causes may be hard to debug. Commented Mar 20, 2011 at 12:58
  • 1
    You're trying to code C using the language C++. Commented Mar 20, 2011 at 13:04

1 Answer 1

5

How about a vector of strings?

#include <vector>
#include <string>

void NPCTalk(std::string const& speaker, std::vector<std::string> const& text)
{
    for (std::vector<std::string>::const_iterator it = text.begin();
                                                  it != text.end(); ++it)
    {
        std::cout << speaker << ": " << *it << std::endl;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

What's this const& for? I'll try that.
You'll get a non-modifiable reference of the object.
@Pig Head: You don't copy the whole vector, which may be slow because it might be pretty big if the NPC likes to talk. A reference behaves similar to a pointer and doesn't make a copy.
Okay - I'm getting the error "Namespace 'std' has no member 'vector'". Odd?
@Pig: Did you #include <vector>?
|

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.