mahadi_mohammad
mahadi_mohammad

Reputation: 161

what a blank "cout" does?

What does it differ a blank cout using or not? This code gives correct answer for using cout<<"";

    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        long long input, ans=1, vagsesh;
        double vag;
        cin>>input;

        while(input>0 || vag>0)
        {
            vag = ((log10(input))/(log10(2)));

            cout<<""; // if this is not used, it leads to a wrong answer

            vagsesh = vag;
            input -= pow(2,vagsesh);
            if(input > 0)
                {
                    ans++;
                }
            if(input==0)
                {
                    break;
                }
        }

        cout<<ans<<endl;

        return 0;
    }

What is done by cout<<""; here?

Upvotes: 3

Views: 332

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27528

cout << "" is not what I would consider a "blank cout". A "blank cout" would be the following:

std::cout;

In fact, std::cout << "" would take manipulators into account. Example:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setw(10);
    std::cout << "";
}

Output: 10 spaces.

Another observable effect of std::cout << "", even without any manipulators, would be when you redirect the output of your program into a file (with something like myprogram.exe > file.txt or ./myprogram > file.txt). std::cout then writes into the file and you could observe a change in the file's modification date even if the contents would remain the same.


As for your code, you have undefined behaviour in it:

    double vag;
    cin>>input;

    while(input>0 || vag>0)

vag is not initialised when you try to read from it. Perhaps this causes the strange behaviour? Because, of course, in an otherwise correct program, cout << "" cannot possibly change the result. Try this to prevent undefined behaviour:

double vag = 0.0;

P.S.: #include <bits/stdc++.h> is not standard C++. You should change it to #include <iostream>, or, generally, to specific header includes. And using namespace std; is a bad habit; even if it doesn't hurt in your example program, beginners sometimes use it at global scope in header files, where it can wreak havoc in the long run.

Upvotes: 7

Related Questions