Invalid operands to binary expression [xcode c++] - c++

Why do I have this error in my code?
void check_letter(string letter, string entry) {
for(int i = 0; i < entry.length(); i++) {
if(entry[i] == letter) {
}
}
}
Invalid operands to binary expression ('std::basic_string<char>::value_type' (aka 'char') and 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char>>'))`
I want to check each letter in the word, so I check all letters of the word in a loop. I tried it on a array char (I made the array with individual letters from the word) and I had the same error.

entry[i] is a char, letter is a std::string - and there is no bool operator==(const char&, const std::string&) so you can't compare the two for equality.
You could change the function to void check_letter(char letter, const string& entry) to make it search for an individual char in entry.
Note: std::string::find can search for an individual char (overload 4) and returns the index of the found char (or std::string::npos if not found).

You are trying to compare a single character with a whole string:
if(entry[i] == letter)
Instead you could write for example:
if ( letter.find( entry[i] ) != std::string::npos ) {
//...
I tried it on a array char (I made the array with individual letters
from the word) and I had the same error
You may not also to compare a whole array with a character.
If for example the variable letter is declared as a character array then you could use standard C string function strchr declared in header <cstring> to determine whether a character is present in the array.
For example:
#include <cstring>
//...
if ( strchr( letter, entry[i] ) != nullptr ) {
//...
Also it is not a good idea to declare the function like:
void check_letter(string letter, string entry);
You should declare parameters as having referenced types as for example:
void check_letter(string &letter, string *entry);
Or you could add qualifier const if strings are not changed in the function like:
void check_letter( const string &letter, const string *entry);
Maybe it would be even better to use std::string_view instead of std::string as the function parameter type.

Related

C++ operator '==' cannot compare string[i] with another string. Compile error

#include <iostream>
using namespace std;
int main()
{
string str = "abcdef";
string x = "a";
if (str[0] == x) {
//do something...
}
return 0;
}
and cannot compile.
"error: no match for ‘operator==’ (operand types are ‘__gnu_cxx::__alloc_traits, char>::value_type’ {aka ‘char’} and ‘std::string’ {aka ‘std::__cxx11::basic_string’})"
std::string except for being a string also provides interface of being a container of chars. So when you use operator[] you access and individual char from this container and you cannot compare a char with a string. If you want to have a single symbol string instead use std::string::substr() with length 1. Or if you want the symbol to compare with another one declare x as being a single char instead of string.
The problem here is that you're comparing a char with a string
str[0] is actually a char
Just need to declare x as char...
#include <iostream>
using namespace std;
int main()
{
string str = "abcdef";
char x = 'a';
if (str[0] == x) {
//do something...
}
return 0;
}
You are asking why your code doesn't compile.
If we look at your code line by line we can see that...
string str = "abcdef";
string x = "a";
if (str[0] == x)
From line one above you declared a string str that stores the set of character encoding values of {a, b, c, d, e, f} either it be ASCII, UTF-X, etc.
On your second line you declare another string x that stores the set of character encoding values of {a} either it be ASCII, UTF-X, etc.
The problem of not compiling does not show up until the expression within the if statement.
The LHS of the expression you are using std::string's operator[] to access the value at the index of its first location in memory. This returns a reference to a character at that indexed location. Then on the RHS of the expression you are comparing the LHS character reference against the std::string named x.
The issue here is that there is no conversion between a reference to a char and std::string and that you have not defined your own operator==() that would do so.
The easiest fix is to change either the LHS to a string or the RHS to a char. There may also be available functions or algorithms within the STL that would do the comparison(s) for you. You can do an online search for that.
You can refer to cppreference:string:basic_string:operator_at for detailed information about std::string's operator[]. And you can search their site for other functions, algorithms and string manipulators and other types of containers. It is probably one of the best resources out there for the C/C++ STL.

comparing s.at(i) to a character?

I'm getting an error that C++ forbids comparison of pointer with character
some sort of -fpermissive error wherever i compare s.at(i) with anything.
string s;
cout<<"Enter the expression";
getline(cin,s);
int i;
for(i=0;i<s.length();i++)
{
if(s.at(i)=="("||s.at(i)=="["||s.at(i)=="{")
push(s.at(i));
}
for(i=0;i<s.length();i++)
{
if(s.at(i)=="]"||s.at(i)==")"||s.at(i)=="}")
{
x=pop();
if (s.at(i)==x)
continue;
else
{enter code here
cout<<"\nInvalid expression";
return 0;
}
}
}
Consider s.at(i)=="(".
The literal "(" is actually a const char[2] type (one element for the (, the other for a NUL-terimator), which decays into a const char* pointer under certain instances, such as this case when using ==.
s.at(i) returns a single char type, which is being compared to a const char* pointer. Your helpful compiler is warning you of this error.
The solution is simple: use '(' instead, which is a single char literal. You can compare a char to a char.
You are encasing characters in double quotes ")" which makes them strings, or char *'s. They should be in single quotes, like ')' so they become char's.

Issue with main arguments handling

I can't compare main() arguments with const char* strings.
Simple code for explaining:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
if(argc>1)
{
for (i=1;i<argc;++i)
{
printf("arg[%d] is %s\n",i,argv[i]);
if(argv[i]=="hello")
printf(" arg[%d]==\"hello\"\n",i);
else
printf(" arg[%d]!=\"hello\"\n",i);
}
}
return 0;
}
Simple compile g++ test.cpp. When I try execute it, I see next thing:
>./a.out hello my friend
arg[1] is hello
arg[1]!="hello"
arg[2] is my
arg[2]!="hello"
arg[3] is friend
arg[3]!="hello"
Whats wrong with my code?
Strings can't be compared with ==, use strcmp:
if (strcmp(argv[i], "hello") == 0)
You have to #include <string.h>
Whenever you use argv[i] == "hello", the operator "==" donot take string as its operand so in actual the compiler compares the pointer to argv[i] with the pointer to constant string "Hello" which is always false and hence the result you are getting is correct, to compare string literals use srtcmp function.
int strcmp(const char *s1, const char *s2);
which compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero, if s1 is found, respectively, to be less than, to match, or be greater than s2.
In this statement
if(argv[i]=="hello")
you compare pointers because the string literal is implicitly converted to const char * (or char * in C) that points to its first character. As the two pointers have different values the expression is always false. You have to use standard C function strcmp instead. For example
if( std::strcmp( argv[i], "hello" ) == 0 )
To use this function you should include header <cstring>(in C++) or <string.h> (in C).

I am trying to compile a simple string but it does not work... why?

My compiler is Code::Blocks. I am trying to eliminate vocals from a character sequence.
#include <iostream>
#include <cstring>
using namespace std;
char sir[256];
int i=0;
int main (){
cout<<"sir=";cin.getline(sir,256);
for (i=strlen(sir);i>0;i--){
if (strstr(sir[i],'aeiou')==0){
strcpy(sir+i,sir+i+1);
break;}}
cout<<"sir="<<sir<<"\n";
return 0;
}
I receive the following error:
error: call of overloaded 'strstr(char&, int)' is ambiguous
note: candidates are:
note: char* strstr(char*, cost char*) near match
But I think the problem is on strstr command...
'aeiou' is not a string literal in c/c++ use "aeiou".
In c/c++ string literal are represented inside " "(double quotes)
Read more here
So, apparently, the idea is to remove vowels. As others have said, use "aeiou" and not 'aeiou'. But you also need to use the right function to check whether you have a vowel. That's strchr(const char* s, int c), not strstr. strchr looks for an occurrence of c in the string that s points to, and returns a pointer to that occurrence, or, if it's not found, a pointer to the terminating nil character. So the test in the original code should be:
if (*strchr("aeiou", sir[i] != '\0')
Personally, I'd write this a bit more succinctly:
if (*strchr("aeiou", sir[i]))
As I wrote in the first comment, the expression
strstr(sir[i],'aeiou')
is wrong for two reasons: ' is for single characters, " is for strings, but the main reason is, that strstr finds the occurance of the whole thing, not of the characters separately.
Try this:
#include <iostream>
#include <cstring>
using namespace std;
char sir[256];
char sir2[256];
int i=0;
int main (){
cout<<"sir=";cin.getline(sir,256);
char* reader = sir;
char* writer = sir2;
while(*reader) {
if(*reader!='a' && *reader!='e' && *reader!='i' && *reader!='o' && *reader!='u') {
*writer = *reader;
++writer;
}
++reader;
}
*writer = '\0';
cout<<"sir="<<sir2<<"\n";
return 0;
}
ststr is defined by two function prototypes
const char* strstr( const char* str, const char* target );
char* strstr( char* str, const char* target );
your call is calling as
strstr(sir[i],'aeiou')
the first arg is a char type, not a char * type, so the compiler does know how to map that to const char * or char *
Also check your loop index as
i=strlen(sir)
will over index the char array and
i > 0
will NOT access the last character.

access first letter of a string in a set c++

I have a set of strings and I need to access each one and compare the first letter of the string to a char and stop if they are the same. How do I go through that? I tried with
char* p;
for (std::set<string>::iterator iter=myset.begin(); iter!=myset.end();iter++)
{p = *iter;
if (p==characterForComparison) return 0;
}
but that does not pass the compiler, it says
error C2440: '=' : cannot convert from 'std::basic_string<_Elem,_Traits,_Ax>' to 'char *'
How do I solve this? What I need is fairly simple, so I need as simple a solution as I can get, just go through all the strings, compare the first letter, and if they are the same, return 0;
To compare first character of std::string just do:
if (!(*iter).empty() &&
(*iter)[0] == characterForComparison)
{
}
To access first element in a string, string provides operator[], front(), or use begin to get reference to first element. see std::string page.
Since your set contains std::strings, dereferencing the iterator gives you a string, not its first character. Use operator [] instead:
p = (*iter)[0];
*iter is a string, try
char p;
//...
p = (*iter)[0]
You have two problems. The first is that you try to assign a std::string object to a char*. The second is if you want the first character, then p should be declared as a character and not a pointer to a character.
And of course, there's really no need to store the character in a temporary variable like p, at least not in such a simple case such as yours. Use it directly from the string like
if ((*iter)[0] == characterForComparison) { /* do something */ }
if you can use C++11:
for(auto s : myset)
{
if(s[0] == characterForComparison)
{
return 0;
}
}
A C++ string is not convertible to a C-style string. *iter gives you a C++ string.
If you want to actually compare the first character of a string, then.
if ((*iter)[0] == 'a')
would do the trick.
If you actually need a const char *, you can use:
p = iter->c_str();
Note however that this is a CONSTANT string, you shouldn't modify it.
You can also use the STL algorithms.
If you can use C++11:
bool set_condition(const char c, const set<string>& s)
{
auto position =
find_if(s.cbegin(), s.cend(), [c](const string& s) { return s[0] == c; } );
return (position != s.cend() );
}
try to wrap the char in an instance of std:string:
std:string comp(characterForComparison);
and
retrieve the first character with [0]