6

Is there any way I can perform both these actions in one line:

fscanf(fp,"%d",&n);
std::cout<<n<<std::endl;

i.e., I am looking for something like:
std::cout<<fscanf(fp,"%d",&n);<<std::endl;

Obviously &n has to be replaced. FILE* has to be used though.

leo valdez
  • 259
  • 1
  • 15
  • If you changed your code to use a `std::istream` instead of a `FILE*`, you could use `cout << in.rdbuf()` IIRC – o11c Jul 07 '18 at 06:48
  • 13
    Why does it have to be in one line? – Galik Jul 07 '18 at 07:27
  • 2
    @Galik Fair point. Code golf? What the compiler emits in the end might be fairly the same like the _inline variant_. – πάντα ῥεῖ Jul 07 '18 at 07:31
  • @Galik There really isn't a reason why. Just looking for some uncommon syntax:). I suppose practically I could always keep it 2 lines. Apologies if this was the wrong site to ask. – leo valdez Jul 07 '18 at 07:39
  • _@leo_ Don't worry, your question is just fine. I can imagine use cases, no matter what @Galik says. – πάντα ῥεῖ Jul 07 '18 at 11:48
  • 1
    @πάνταῥεῖ Of course, it can be important to save precious bytes on the hard disk. All those line-endings in the source code add up! ;-) – Galik Jul 07 '18 at 11:57
  • 2
    @Galik I more tought about how to inject functions that don't follow the signature `ostream& foo(ostream &, T&)` into a bigger output formatting sequence, when you want to output T after manipulation it somehow. Readability of such code matters. – πάντα ῥεῖ Jul 07 '18 at 12:02

1 Answers1

12

Yes it is possible to do the fscanf() call inline using the , operator:

#include <iostream>

int main()
{
    int n = 0;
    std::cout<< (fscanf(stdin,"%d",&n),n)<<std::endl;
}

See a live demo here.


For the present example there aren't many good use cases, but I can think at least this one to save formatting readability:

Say you have a type T, providing an operation like void T::update(); and you're too lazy to wrap calls to T::update() into something like std::ostream& update(ostream&,T&) you can use this trick:

std::array<std::array<T,4>,4> m { // A matrix of T
    { T::create() ,T::create() ,T::create() ,T::create() } ,
    { T::create() ,T::create() ,T::create() ,T::create() } ,
    { T::create() ,T::create() ,T::create() ,T::create() } ,
    { T::create() ,T::create() ,T::create() ,T::create() }
};

// ....

using u = T::update;
std::cout << "Current matrix state:\n" <<
(m[0][0].u(),m[0][0]) << ',' (m[0][1].u(),m[0][1]) << ',' (m[0][2].u(),m[0][2]) << ',' (m[0][3].u(),m[0][3]) << '\n' <<
(m[1][0].u(),m[1][0]) << ',' (m[1][1].u(),m[1][1]) << ',' (m[1][2].u(),m[1][2]) << ',' (m[1][3].u(),m[1][3]) << '\n' <<
(m[2][0].u(),m[2][0]) << ',' (m[2][1].u(),m[2][1]) << ',' (m[2][2].u(),m[2][2]) << ',' (m[2][3].u(),m[2][3]) << '\n' <<
(m[3][0].u(),m[3][0]) << ',' (m[3][1].u(),m[3][1]) << ',' (m[3][2].u(),m[3][2]) << ',' (m[3][3].u(),m[3][3]) << '\n' <<
flush;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190