pighead10
pighead10

Reputation: 4305

String Variable Argument Lists in C++

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

Upvotes: 4

Views: 3398

Answers (1)

fredoverflow
fredoverflow

Reputation: 263370

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;
    }
}

Upvotes: 5

Related Questions