Reputation: 107
Why can't I compare UserInput[i]
to "*"
? The compiler says "ISO c++ forbids comparison between pointer and integer". Where is the integer? The only one I see on that line is i
, which is used for locating the specific character.
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main(){
char UserInput[4] = "2*3";
for (int i=0; i< strlen(UserInput); i++)
{
if(UserInput[i] == "*")
{
cout<<"There is multiplication Involved \n";
}
}
return 0;
}
Upvotes: 1
Views: 861
Reputation: 7123
It's a little bit tricky.
All inside " " is a string - array of chars. Array in c/c++ is pointer to first element of array.
Each single element of string is char, which is converted to int.
At the end, compiler says that it's not possible to compare this two items.
You need to do like this:
if(UserInput[i] == '*')
In this case you compare two chars with no problem.
PS If you want to determine presence of one string in another string, you should use strstr()
.
Upvotes: 0
Reputation: 3632
if(UserInput[i] == "*")
Will issue a warning because of ""
"*"
is not char. "*"
is a const char*
.
Comparison between pointer and integer (int
and const char *
) is not possible
change it to
if(UserInput[i] == '*')
Upvotes: 2
Reputation: 12641
Additionally, use std::string
instead of char arrays
#include <iostream>
#include <string>
using namespace std;
int main() {
string UserInput = "2*3";
for (int i = 0; i < UserInput.length(); i++) {
if (UserInput[i] == '*') {
cout << "There is multiplication Involved \n";
}
}
return 0;
}
Upvotes: 1
Reputation: 206667
Where is the integer?
Your conditional expression is UserInput[i] == "*"
.
In the expression UserInput[i]
is of type char
. In many of the binary operations, char
is promoted to int
before the operation is carried out. As far as the compiler is concerned, it is comparing an int
with "*"
, which is of type const char[2]
but decays to a pointer in the expression.
What you need to do is compare the char
with the character constant '*'
. Use
if(UserInput[i] == '*') {
Upvotes: 5