if else statement basic problem

This program keep on having [Error] 'else' without a previous 'if'. What is the problem exactly?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <iostream>
#include<string>
using namespace std;
int main()
{
	string liq;
	double e,p;
	cout<<"pls enter liquid";
	cin>>liq;
	
	if (liq=="water"||liq=="WATER")
	e=2.15;
	p=999.8;
	
	else if(liq=="oil"||liq=="OIL")
	e=1.35;
	p=920;
	else if (liq=="ethy alcohol"||liq=="ETHYL ALCOHOL")
	e=1.06;
	p=810;
	else if (liq=="mercury"||liq=="MERCURY")
	e=28.5;
	p=13595;	
	else 
	cout<<"pls key in again"<<endl;

}
cout<<e<<p;
return 0;
The problem is that you are not using curly brackets. Use Curly brackets.

If you dont use curly brackets, loops, statements etc they only see the first line of code.
Always use them :p

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int main(){

	string liq;
	double e, p;
	cout << "pls enter liquid";
	cin >> liq;

	if (liq == "water" || liq == "WATER")
	{
		e = 2.15;
		p = 999.8;
	}
	else if (liq == "oil" || liq == "OIL")
	{
		e = 1.35;
		p = 920;
	}
	
	else if (liq == "ethy alcohol" || liq == "ETHYL ALCOHOL")
	{
		e = 1.06;
		p = 810;
	}
	
	else if (liq == "mercury" || liq == "MERCURY")
	{
		e = 28.5;
		p = 13595;
	}

	else
	{
		cout << "pls key in again" << endl;
	}
}


And also, why is the cout statement outside of main?

1
2
cout<<e<<p;
return 0;


move these two inside.

For the guy below me, use code tags. <> under the format section.
Last edited on
as long as your if statement consists of more than one line, for example (in your code you have e=1.35 and p= 920) you need to put them between curly brackets "{}". You also have another mistake at the end of your code, "return 0;" should come before the curled bracket.
so it should be:
cout<<e<<p;
return 0;
}

Corrected code:

if (liq=="water"||liq=="WATER")
{e=2.15;
p=999.8;}

else if(liq=="oil"||liq=="OIL")
{e=1.35;
p=920;}
else if (liq=="ethy alcohol"||liq=="ETHYL ALCOHOL")
{e=1.06;
p=810;}
else if (liq=="mercury"||liq=="MERCURY")
{e=28.5;
p=13595;}
else
cout<<"pls key in again"<<endl;
cout<<e<<endl<<p;
return 0;
}

Topic archived. No new replies allowed.