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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With