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);
}
}
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);
}