1

I have this code:

#include <iostream>
using namespace std;

double sqrt(double n)

{
double x;
double y = 2; //first guess is half of the given number
for (int i = 0; i<50; i++)
{
    if (n>0)
    {
        x = n / y;
        y = (x + y) / 2;
    }
    if (n==0)
    {
        return 0;
    }
}

return y;
}

int main()
{
cout << "Square Root Function" << endl;
double z=0;
while (true)
{
    cout << "Enter a number = ";
    cin >> z;
    if (z<0)
    {
        cout<<"enter a positive number"<<endl;
        continue;
    }
    cout <<"the square root is "<< sqrt(z) << endl;
}

return 0;
}

and it would show this result:

Square Root Function
 Enter a number = 12
 the square root is: 3.4641

but now the code is showing these results:

Square Root Function
1 //my input
Enter a number = the square root is 1
2 //my input
Enter a number = the square root is 1.41421

It seems like the cout will only show up first if an endl was added after the string. This just started happening recently. Is there a way I can fix this to show the proper output?

David
  • 13
  • 2

1 Answers1

0

std::cout uses buffered output, which should always be flushed. You can achieve this by using std::cout.flush() or std::cout << std::flush.

You can also use std::cout << std::endl, which writes a line break and then flushes, thats the reason your code shows this behavior.

Change your int main() to

int main(){
    std::cout << "Square Root Function" << std::endl;
    double z=0;
    while (true){
        std::cout << "Enter a number = " << std::flush
                                          /*^^^^^^^^^^*/
        std::cin >> z;
        if (z<0){
            std::cout << "enter a positive number" << std::endl;
            continue;
        }
        std::cout << "the square root is " << sqrt(z) << std::endl;
    }
}

EDIT: The XCode Problem Since you use XCode another thing could cause trouble. It seems like XCode doesn't flush buffers until a line break; flushing doesn't help. We had several questions about it lately (e.g. C++ not showing cout in Xcode console but runs perfectly in Terminal). It seems to be a bug in a XCode version.

Try to flush your buffer as described by me and try to compile it using terminal. If it works there your code is fine and it's an XCode issue.

Community
  • 1
  • 1
dtell
  • 2,488
  • 1
  • 14
  • 29