No operator "==" matches these operands

I am trying to see if the first part of the string is equal to 0, but the "==" is cause me problems. Any ideas?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Control Unit initialize
  int count = cu.getPC();

  for (int i = 0; i < im1.size(); i++)
  {
	  string binary = im1.fetch(count);
	  cout << "Instruction memory index "<< count << ": " << binary << endl;
	  cout << binary.substr(0,1) << " " << count << endl;
	  string first = binary.substr(0,1);
	  if (first == 0)
	  {
		  // Send to ALU
	  }
	  else
	  {
		  // Keep in Control Unit
	  }
	  
	  count++;
  }
you're trying to compare a string to an integer, which is nonsensical.

You also don't need to use substr() to get a single character. Instead you can just use the [bracket operator]

Example:

1
2
3
4
5
6
7
8
// cout << binary.substr(0,1) << " " << count << endl; // <- bad

cout << binary[0] << " " << count << endl; // <- good

/*string first = binary.substr(0,1);  // <-bad
	  if (first == 0)*/  // <- bad

if(binary[0] == '0') // good 


Note not only am I using the [brakets] here, but I'm also comparing to '0' and not . '0' is the character '0' (ie: the ASCII representation of the numerical digit '0'), whereas 0 is the integral number 0.
Ok so that works for one index...how about if I wanted to grab the first five lines of the string?
Last edited on
You could use a for loop and store them all in a new string:

1
2
3
4
5
6
7
8
9
string a ;
string b = "12345" ;

cout << "Enter a string: " ;
cin >> a ;

for (int i = 0 ; i < 5 ; i ++ ) b [i] = a [i] ;

cout << "The first five characters of your string are "" << b << "" ." ;
Last edited on
Well in that case you could use substr. It just doesn't make sense to use substr for 1 character is all.

1
2
if(binary.substr(0,5) == "12345")
  //  ... 
Topic archived. No new replies allowed.