C++ 中的字符串变量参数列表

pig*_*d10 4 c++ string arguments list variadic-functions

我正在尝试使用可变参数列表来使基于文本的 RPG 中的 NPC 轻松交谈。有这么多错误,我什至懒得发布它们 - 我想我使用这个太错误了,你不需要输出。如果你这样做,我当然会发布它。

这是您需要的两个文件:

//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
Run Code Online (Sandbox Code Playgroud)

另一个:

//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
Run Code Online (Sandbox Code Playgroud)

fre*_*low 5

字符串向量怎么样?

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)