我的 va_start/va_end macroses 工作不正常
My va_start/va_end macroses work wrong
大家;
请帮我解决这个问题:
#include "fstream"
#include "iostream"
#include "string"
#include "stdarg.h"
using namespace std;
void f(char a,...)
{
cout<<a;
va_list list;
va_start(list,a);
cout<<va_arg(list,char)<<" ";
va_end(list);
};
int main()
{
f('a','b','c','d');
system("pause >> void");
return 0;
}
结果必须是这个
a b c d
但它只给出了
a b
我做错了什么?
两个问题:
至少在某些编译器上,将 char
传递给可变参数函数会提升为 int
。在我敲出一些测试代码并且编译器唠叨之前,我自己已经忘记了这个。这意味着您的 8 位很可能只是变成了 32 位或 64 位。这会引起相当不错的 Kaboom!
和
cout<<va_arg(list,char)<<" ";
对va_arg的每次调用都会return一个变量,在本例中为字符'b'。要获得 'c' 你必须再次调用它。等等...
这给您留下了一个有趣的问题,即知道何时停止调用 va_arg。
这是一个便宜的技巧:
#include "fstream"
#include "iostream"
#include "string"
#include "stdarg.h"
using namespace std;
void f(char a,...)
{
cout<<a;
va_list list;
va_start(list,a);
char ch = (char)va_arg(list,int);
while (ch != '[=11=]') // stopping on null
{
cout << " " << ch; // cout << a didn't have a space appended so I
// reversed the placement here
ch = (char)va_arg(list,int);
}
va_end(list);
};
int main()
{
f('a','b','c','d', '[=11=]'); // note the added null.
cout << endl;
system("pause >> void"); // better ways to do this cin >> junk, for one
return 0;
}
大家;
请帮我解决这个问题:
#include "fstream"
#include "iostream"
#include "string"
#include "stdarg.h"
using namespace std;
void f(char a,...)
{
cout<<a;
va_list list;
va_start(list,a);
cout<<va_arg(list,char)<<" ";
va_end(list);
};
int main()
{
f('a','b','c','d');
system("pause >> void");
return 0;
}
结果必须是这个
a b c d
但它只给出了
a b
我做错了什么?
两个问题:
至少在某些编译器上,将 char
传递给可变参数函数会提升为 int
。在我敲出一些测试代码并且编译器唠叨之前,我自己已经忘记了这个。这意味着您的 8 位很可能只是变成了 32 位或 64 位。这会引起相当不错的 Kaboom!
和
cout<<va_arg(list,char)<<" ";
对va_arg的每次调用都会return一个变量,在本例中为字符'b'。要获得 'c' 你必须再次调用它。等等...
这给您留下了一个有趣的问题,即知道何时停止调用 va_arg。
这是一个便宜的技巧:
#include "fstream"
#include "iostream"
#include "string"
#include "stdarg.h"
using namespace std;
void f(char a,...)
{
cout<<a;
va_list list;
va_start(list,a);
char ch = (char)va_arg(list,int);
while (ch != '[=11=]') // stopping on null
{
cout << " " << ch; // cout << a didn't have a space appended so I
// reversed the placement here
ch = (char)va_arg(list,int);
}
va_end(list);
};
int main()
{
f('a','b','c','d', '[=11=]'); // note the added null.
cout << endl;
system("pause >> void"); // better ways to do this cin >> junk, for one
return 0;
}