1
\$\begingroup\$

I'm golfing a program to sum two numbers in C++.

Example:

10 3
13

I found out that this problem can be solved in 54 symbols (without spaces and so on) using C++. My code (63 symbols):

#include <iostream>
main() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b;
}

I have no idea how to make my program shorter. Can you help me, please?

\$\endgroup\$
11
  • \$\begingroup\$ Do the numbers have to come from STDIN? \$\endgroup\$ – James Jun 5 '17 at 19:09
  • \$\begingroup\$ DJMcMayhem, yes. \$\endgroup\$ – eaglemango Jun 5 '17 at 19:11
  • \$\begingroup\$ I don't think you can beat that if you have to use STDIN. \$\endgroup\$ – Magic Octopus Urn Jun 5 '17 at 19:18
  • 3
    \$\begingroup\$ Your program can not run according to c++ standard. the function main should have a return type. \$\endgroup\$ – rahnema1 Jun 6 '17 at 2:25
  • 9
    \$\begingroup\$ @CalculatorFeline This is a perfectly fine tips question, no reason to close it. \$\endgroup\$ – TheLethalCoder Jun 6 '17 at 9:59
5
\$\begingroup\$

48 bytes

How about...

#include<cstdlib>
main(){system("tr \\  +|bc");}

...not using C++?


  • The call to system runs commands on your shell (<cstdlib> declares system).
  • tr \\ + executes the command tr, translating spaces to + (so the input34 45 becomes 34+45).
  • | pipes tr's STDOUT into bc's STDIN.
  • bc performs equations in STDIN and prints the result to STDOUT.
\$\endgroup\$
4
  • \$\begingroup\$ Can you explain how does it work? I tried to run that program on Linux, but the next error ocured: bc: not found \$\endgroup\$ – eaglemango Jun 6 '17 at 11:02
  • 4
    \$\begingroup\$ @eaglemango Well, you have to install bc. \$\endgroup\$ – jimmy23013 Jun 6 '17 at 11:06
  • \$\begingroup\$ Mind if I edit in an explanation and some links? \$\endgroup\$ – MD XF Dec 28 '17 at 19:39
  • \$\begingroup\$ @MDXF Fine. (15 chars) \$\endgroup\$ – jimmy23013 Dec 29 '17 at 3:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.