2011-03-20 30 views
2

我试图使用可变参数列表在基于文本的RPG中轻松地创建NPC。有很多错误,我甚至不打扰他们发布 - 我收集我使用这个错误,你不会需要输出。 如果你这样做,当然我会发布它。C++中的字符串变量参数列表

这里的两个文件,你需要:

//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 

而另外一个:

//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 
+0

如果你想使用'std :: string',你必须包含''。 – svens 2011-03-20 12:47:57

+2

尝试将非POD类型(如'std :: string')传递给可变参数函数并不是一个好主意。结果将是不可移植的,它造成的问题可能很难调试。 – 2011-03-20 12:58:11

+1

您正在尝试使用C++语言对C进行编码。 – Nawaz 2011-03-20 13:04:10

回答

3

如何串的载体?

#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; 
    } 
} 
+0

这是什么'const&'for?我会尝试的。 – pighead10 2011-03-20 12:57:06

+0

你会得到一个不可修改的对象引用。 – RedX 2011-03-20 12:59:27

+0

这是什么意思? – pighead10 2011-03-20 13:01:18