首页 > 解决方案 > How I can stop the " while loop " if the user enter number <0?

问题描述

in this example :

    int numbers=0 ,sum=0;

    while (numbers >=0)
    {
        cout<<"Enter positive numbers: ";
        cin>>numbers;
        sum += numbers;
    }
    cout<<"The result = "<<sum<<"\n";

Can u help me what I should to do please?

标签: c++

解决方案


In the loop, you'll have to deal with two situations.

  1. The user enters invalid input or EOF.
  2. The user enters a number less than 0.

For the first, you'll need to use:

if ( cin >> numbers )
{
    // Reading to numbers was successful.
}
else
{
   // Deal with the error.
}

For the second situation, you'll need to use:

if ( numbers < 0 )
{
    break;
}

Put it all together,

while ( true )
{
    cout << "Enter positive numbers: ";
    if ( cin >> numbers )
    {
       if ( numbers < 0 )
       {
          break;
       }
    }
    else
    {
       // Deal with error. Perhaps break out of the loop too?
       break
    }
    sum += numbers;
}
cout << "The result = " << sum << "\n";

推荐阅读