Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a character in a string equals "w"

I am failing to compare characters of a string in my program, I made a simpler version to showcase the problem:

#include <iostream>
using namespace std;


int main() {
        string s = "Hello world!";

        for(int i = 0; i<s.size(); i++) {
                if(s[i] == "w") {
                        cout << "This is a w!" << endl;
                }
        }
}

It returns this error:

so.cpp:10:25: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
10 | if(s[i] == "w")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

"w" is a pointer to the C string ['w', '\0'] in memory. You want to use single quotes instead so you are only comparing the character literal.

 if (s[i] == 'w') {
     cout << "This is a w!" << endl;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading