Why doesn't the Variadic Template Function inside a while loop print to the console?

Viewed 81

I want to try the flag-controlled while-loop statement that prints a statement and accept user input using variadic template function? Is this possible?

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }

template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a;

    while(a > 100) {
        write("Enter a number: ");
        read(a);
    }
}
2 Answers
int a;

You declare a, but not initialize it, which means a is uninitialized and can hold some random value.

You can fix this problem by initializing a with a value bigger than 100, for example:

int a = 101;

So your code should look like this:

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }

template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a = 101;

    while(a > 100) {
        write("Enter a number: ");
        read(a);
    }
}

As mentioned in comment, the variable a is not initialized. Hence, the variable contains a garbage value, so it will result into a runtime error.

Therefore first initialize the variable, then run a while loop on it. And the code need to take the user input using variadic template function. So you can do this:

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }

template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a;

    // To initialize a
    write("Enter a number: ");
    read(a);
    while(a > 100) {
        write("Enter a number: ");
        read(a);
    }
}

If do-while loops are allowed, then the below is also a possible solution:

#include <iostream>

template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }
template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }

auto main() -> int {

    int a;

    do {
        write("Enter a number: ");
        read(a);
    }while(a > 100);
}
Related