Good day guys, I'm a beginner of c++ programming, and suffering from a petty problem.
This code is to set typed values upperbound.
#include "../../std_lib_facilities.h"
int change(int a, int b) {
if (a > b) {
int c = a; a = b; b = c;
}
return a, b;
}
int main() {
int a, b, c;
while (cout << "Type 3 numbers: \n" && cin >> a >> b >> c) {
a,b = change(a, b);
b,c = change(b, c);
a,b = change(a, b);
cout << a << ", " << b << ", " << c << "\n";
}
simple_error("You typed invalid number.\n");
}
In this case, for instance, when I type '2 5 3' it returns '2, 5, 5' not '2, 3, 5' as expected. I found that
b,c = change(b, c);
this line has problem debugging by cout, but I don't know the reason. How could I solve it? Thanks for reading.
The code seems to be trying to use certain C++ idioms, but doesn't do them correctly. I've tried to correct them here for you. (Otherwise, David Grayson’s answer is also good, and also idiomatic C++.)
To do a destructured binding, you'll need to use a tie
.
To return a pair of values, you'll need to return a pair
or tuple
. And then do a return {a, b};
to return the a
and b
as a pair (or tuple).
The successful input should skip doing the simple_error
handler. Here, I've done it by doing an early return EXIT_SUCCESS;
.
#include <cstdlib>
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
using std::cin;
using std::cout;
using std::pair;
using std::string;
using std::tie;
namespace {
auto change(int a, int b) -> pair<int, int> {
if (a > b) {
int c = a; a = b; b = c;
}
return {a, b};
}
void simple_error(string const& s) {
cout << "Error: " << s;
}
} // anon
int main() {
int a, b, c;
while (cout << "Type 3 numbers: \n" && cin >> a >> b >> c) {
tie(a, b) = change(a, b);
tie(b, c) = change(b, c);
tie(a, b) = change(a, b);
cout << a << ", " << b << ", " << c << "\n";
return EXIT_SUCCESS;
}
simple_error("You typed invalid number.\n");
return EXIT_FAILURE;
}