-1
#include <iostream>
using namespace std;

int main()
{
    string s[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int a, b;
    cin >> a >> b;
    for (int i = a; i <= b; i++)
        (i >= 1 && i <= 9) ? printf("%d\n", s[i - 1]) : i % 2 ? printf("odd\n") : printf("even\n");
    return 0;
}

I am using a ternary operator to print integer into word if it lies between 1 to 9 otherwise printing whether it's even or odd. I am not able to use cout in ternary operator and if I used printf then it's printing a character. can anybody tell me how to do that. I wanted to do the entire stuff in one line, is it possible?

  • 1
    `s[i - 1]` is a `string`, so you can't print it with `printf` and `%d`. If you *must* use `printf` then try `printf("%s\n", s[i - 1].c_str())` instead. But you should better use `cout` and readable code rather that cryptic one-liners. – dxiv Jan 21 '21 at 07:43
  • use `%s` to format a string – limserhane Jan 21 '21 at 07:44
  • Does this answer your question? [printf with std::string?](https://stackoverflow.com/questions/10865957/printf-with-stdstring) – Lukas-T Jan 21 '21 at 07:45
  • Interesting that you can't use `cout`. Seems to work fine over here: https://ideone.com/RCIbSl – user4581301 Jan 21 '21 at 07:47
  • You've already included `` (but not `` that is needed for `std::printf`) so _why_ use `printf` instead of `std::cout` ? – Ted Lyngmo Jan 21 '21 at 07:48
  • Re: "I am using a ternary operator" -- why? An ordinary `if ... else if ...` ladder would be much clearer. A ternary **operator** is intended to compute a value; the code here doesn't use that value, so there's no need for this obfuscation. – Pete Becker Jan 21 '21 at 14:33

2 Answers2

3

You can use cout. Like so:

#include <iostream>


int main()
{
    std::string s[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    int a, b;
    std::cin >> a >> b;
    for (int i = a; i <= b; i++)
        std::cout << ((i >= 1 && i <= 9) ? s[i-1]: (i % 2) ? "odd": "even") << "\n";
    return 0;
}
alex_noname
  • 26,459
  • 5
  • 69
  • 86
2

%d prints decimal numers to the console. To print strings, you need the %s token and make sure that you get the const char* of it using s[i - 1].c_str().

D-RAJ
  • 3,263
  • 2
  • 6
  • 24