What is wrong with this?

when I enter The code below it says 2 errors and both are :
too many characters in constant
too many character in constant

#include <iostream>
using namespace std;
int main()
{
int b,q;
cout<<"Please enter the barcode"<<endl;
cin>>b;
if (b='access')
{
cout<<"Please enter the QTY"<<endl;
cin>>q;
cout<<600.00*q<<endl;
}
else if (b='pencil')
{
cout<<"Please enter the QTY"<<endl;
cin>>q;
cout<<1.00*q<<endl;
}
return 0;
}
It would help if you indicated what line the problem was on.

Fix the quotes in:
else if (b='pencil')
the single quotes ' are used for character constants. So this is wrong:
'pensil'
and this is right:
'p'
You need to use a string for your barcode variable and strings need to be enclosed in "" type quotes not '' which are for single characters.

Also when you want to compare values in C++ use the double equals syntax a == b. When you say a = b you make a equal to b rather than testing their equality.

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
#include <iostream>
#include <string> // use string

using namespace std;

int main()
{
//	int b, q; // b should not be int

	string b;
	int q;

	cout << "Please enter the barcode" << endl;
	cin >> b;

	// assignment instead of comparison, wrong quotes
	// if(b = 'access')
	if(b == "access") // note == for comparing
	{
		cout << "Please enter the QTY" << endl;
		cin >> q;
		cout << 600.00 * q << endl;
	}
	else if(b == "pencil") // same here == and ""
	{
		cout << "Please enter the QTY" << endl;
		cin >> q;
		cout << 1.00 * q << endl;
	}
	return 0;
}
Last edited on
int b is integer type, not a string. You can write #include<string> and string b;. What's more, strings must be enclosed within double quotes.
Topic archived. No new replies allowed.