Concatenate integer and space/newline for cout in C++

I'm trying to print out integers and space/newline for a nicer output, for example, every 20 integers in a row with ternary operator.
In C I could do it with:

printf("%d%s",tmp_int, ((j+1)%20) ? "\t":"\n"); 

but could not figure out the equivalent in C++:

cout << ((j+1)%20)? string(tmp_int+"\t"):string(tmp_int+"\n");
cout << ((j+1)%20)? to_string(tmp_int+"\t"):to_string(tmp_int+"\n");

Can anyone correct my code for the right trick?
Thanks!

Plus does not mean append, that's only a feature of std::string. What you are doing is adding a number to a number.

I don't think you need std::string at all. Just let cout print them:

cout << tmp_int << ((j+1)%20)?"\t":"\n";
1 Like

In addition to what Corona688 has already said; if you were trying to append a <newline> to the string returned by string() or to_string() using std::string that would be coded as:

to_string(tmp_int)+"\n";

not:

to_string(tmp_int+"\n");
1 Like

Thanks!
I'm surprised the problem seems to be with the higher precedence of the operator "<<" in this case

cout  << tmp_int << ((j+1)%20) ? "\t":"\n";

which needs to be bracketed as

cout  << tmp_int << (((j+1)%20) ? "\t":"\n");

Did I miss anything?

No idea what's going on there. If it mistook it for some other operator there'd be a syntax error since ? and : can't do much else, but it's definitely not working. Perhaps it's being taken to be the wrong type.