0

What is the equivalent statement of this commented line in C++ :

#include <iostream>
int main()
{
    int x, y;
    cin >> x >> y;
    // equivalent of this line in c++ : printf("%d\n", x > y ? x : y); 
    return 0;
}
  • 4
    C functions still work in C++, do you really need a replacement? – Mark Ransom Jun 30 '22 at 03:22
  • 14
    `std::cout << (x > y ? x : y) << "\n";` – Eljay Jun 30 '22 at 03:22
  • Is there a reason the C-style function doesn't work for you? – Joel Hager Jun 30 '22 at 03:23
  • Have a look at std::string, std::cout and std::format (C++20). https://www.learncpp.com/cpp-tutorial/output-with-ostream-and-ios/, https://en.cppreference.com/w/cpp/utility/format/format – Pepijn Kramer Jun 30 '22 at 03:24
  • It works but I just wanted to write the code differently because I'm beginner to c++ and don't know much about it. – Nazmus Sakib Sibly Jun 30 '22 at 03:25
  • It is a good question, printf has its issues. https://stackoverflow.com/questions/2872543/printf-vs-cout-in-c – Pepijn Kramer Jun 30 '22 at 03:27
  • 1
    Depends on what you mean by equivalent. Assuming there is an `#include ` (or `#include `) and a `using namespace std` directive in effect (which is one option to use `cin` without fully qualifying as `std::cin`), the code will compile and work the same way "as is" in C++. If you want the same output to standard output, but using `std::cout` instead of calling `printf()`, `std::cout << (x > y> ? x : y) << '\n'` will produce the same effect. You can also avoid doing `x > y ? x : y` by adding `#include ` and using `std:max(x,y)` instead. – Peter Jun 30 '22 at 04:07
  • 6
    `std::cout << std::max(x, y) << '\n';` would be a more C++-ish way to do it. – paddy Jun 30 '22 at 04:09
  • 1
    @NazmusSakibSibly then please [read a good book](https://stackoverflow.com/q/388242/995714) because SO isn't a place for learning and you'll quickly be turned down by that – phuclv Jun 30 '22 at 06:25

1 Answers1

1

You could use std::format, which is very similar to the printf function but it only appeared in C++20.

#include <iostream>
#include <format>

int main() {
    int x, y;
    std::cin >> x >> y;
    std::cout << std::format("{0}", x > y ? x : y) << std::endl;
    return 0;
}
Alvov1
  • 157
  • 1
  • 2
  • 10