C++ 我的VAU start/VAU end宏工作错误
每个人 请帮我做这个:C++ 我的VAU start/VAU end宏工作错误,c++,function,macros,C++,Function,Macros,每个人 请帮我做这个: #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(li
#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
我做错了什么?两个问题:
至少在某些编译器上,将char传递到varargs函数会被提升为int。我自己也忘记了这一点,直到我敲出一点测试代码,编译器开始唠叨。这意味着你的8位很可能变成了32或64位。这会引起一个非常好的笑声 及 每次调用va_arg都将返回一个变量,在本例中为字符“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 != '\0') // 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', '\0'); // note the added null.
cout << endl;
system("pause >> void"); // better ways to do this cin >> junk, for one
return 0;
}
你做的一件事是在C++中使用VAYARG。如果你是一个自学成才的人,现在就停下来吧,因为它没什么用处。你可能会在某个时候偶然发现不得不使用它,但你最好在那时候学习。如果你在大学里学习这些,或者告诉你的教授不要教你垃圾,那么上面的评论中提到的是VAYARGS,而不是C++。我不确定这从句子结构上看是否明显。至少在某些编译器上,将char传递到varargs函数会被提升为int。s/部分/全部符合要求/。这是标准要求的,称为默认参数升级。非常感谢您的确认。我怀疑如果没有其他东西的话,便携性也是如此,但我不确定。
cout<<va_arg(list,char)<<" ";
#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 != '\0') // 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', '\0'); // note the added null.
cout << endl;
system("pause >> void"); // better ways to do this cin >> junk, for one
return 0;
}