Reputation: 11
if (Mileage > 0) do
{
calculateMileage();
cout << "The cost of shipment over " << setprecision(2) << Mileage << " miles is \234" << variableShippingCost << ".";
cout << "\n \n";
system("pause"); //to hold the output screen
return(0);
}
else
{
cout << "\n ERROR: The distance should be a positive value.";
system("pause"); //to hold the output screen
return(0);
}
I have no clue why but Visual Studio 12 is bringing an error on the else saying that it expects a while. I've done many if else statements before and also in this program that work fine so could anyone help me to understand why in this case it is not happy?
Upvotes: 0
Views: 508
Reputation: 422
Because you are doing it wrong! C++ has if-else statements and do-while statements. do
expects a while
following itself, meanwhile while
can be used independently.
Similarly, if
can be used independently, but else
expects an if
before itself.
Upvotes: 0
Reputation: 4571
The correct syntax is:
if (...)
{...} else {...}
when using if
and
do {...}
while (...);
when using do...while
.
There's no if() do
statement in C/C++!
Upvotes: 4
Reputation: 512
dont use do. that is for a while loop and the correct syntax for using that is
do{
...code here...
} while(some condition is true)
what you want is
if (Mileage > 0) //there is an implicit then here no need to do anything here
{
calculateMileage();
cout << "The cost of shipment over " << setprecision(2) << Mileage << " miles is \234" << variableShippingCost << ".";
cout << "\n \n";
system("pause"); //to hold the output screen
return(0);
} //<<<------if you really wanted to use the do (which you shouldnt) put a while here.
else
{
cout << "\n ERROR: The distance should be a positive value.";
system("pause"); //to hold the output screen
return(0);
}
Upvotes: 0
Reputation: 3380
You have a do
after the if
, so the compiler expects a while
after the do
block.
if (Mileage > 0)
{
do
{
calculateMileage();
//etc...
} while (something);
}
else
{
//etc...
}
or
if (Mileage > 0) // no `do` here
{
calculateMileage();
//etc...
}
else
{
//etc...
}
Upvotes: 0