如何让我的va_list参数重复自己? [英] How can I get my va_list arguments to repeat itself?

查看:264
本文介绍了如何让我的va_list参数重复自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次使用 va_list 和东西,所以我真的不知道我在做什么。好吧基本上我有一个数字(1,2,3,4,5)在函数排序,我让他们打印出来。这很好。

This is my first time working with va_list and stuff so I don't really know what I'm doing. Okay basically what I have is a bunch of numbers (1, 2, 3, 4, 5) in the function ordered and I get them to print out. This works fine.

#include <iostream>
#include <cstdarg>

using namespace std;

void ordered(int num1, double list ...);

void main()
{ 
    ordered(5, 1.0, 2.0, 3.0, 4.0, 5.0);
}

void ordered(int num1, double list ...)
{
    va_list arguments;

    va_start(arguments, num1);

    list = va_arg(arguments, double);
    cout << "There are " << num1 << " numbers" << endl;

    do { 
        cout << list << endl; // prints out 1 then 2 then 3 then 4 then 5
        list = va_arg(arguments, double);
    } while (list != 0);

    // at this point, list = 0

    va_end(arguments);
}

问题是,在 va_end ; 或之前,我想让程序第二次打印我的列表;基本上会再次打印出1,2,3,4,5,而不会产生其他功能。我试着复制代码:

the problem is, after the va_end(arguments); or before it, I would like to get the program to print out my list a second time; basically print out 1, 2, 3, 4, 5 once more, without making another function. I tried to duplicate the code:

va_start(arguments, num1);

do { 
    cout << list << endl;
    list = va_arg(arguments, double);
} while (list != 0);

va_end(arguments);

没有成功。如何让程序再次重复 list ,或者不可能在同一个函数中再次执行呢?

without success. How can the program to repeat list once more, or is it not possible to do it again in the same function?

推荐答案

这是一个有效的实现:

#include <iostream>
#include <cstdarg>

using namespace std;

void ordered(int num1, ...); // notice changed signature


int main(int,char**)
{ 
    ordered(5, 1.0, 2.0, 3.0, 4.0, 5.0);
    return 0;
}

void ordered(int count, ...) // notice changed signature
{
    va_list arguments;

    va_start(arguments, count);

    cout << "There are " << count << " numbers" << endl;

    double value = 0.0;

    // notice how the loop changed
    for(int i = 0; i < count; ++i) { 
        value = va_arg(arguments, double); 
        cout << value << endl; // prints out 1 then 2 then 3 then 4 then 5
    } 

    // at this point, list = 0

    va_end(arguments);

    va_list arg2;
    va_start(arg2, count);

    cout << "There are " << count << " numbers" << endl;

    for(int i = 0; i < count; ++i) { 
        value = va_arg(arg2, double);
        cout << value << endl; // prints out 1 then 2 then 3 then 4 then 5
    } 

    // at this point, list = 0

    va_end(arg2);

}

这篇关于如何让我的va_list参数重复自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆