samedi 5 décembre 2020

C++ won't let me compare characters in a string [closed]

So I'm trying to make this program where you input a string and the program finds all the instances of a character inside the string. I have this code

#include <iostream>;
using namespace std;

int main() {
    string word = "Hello there";

    for (int i = 0; i < word.length(); i++) {
        if (word[i] == "t") {
            cout << "Found letter at index " << i << endl;
        }
    }

    return 0;
}

But I keep getting this error

||=== Build: Debug in HelloWorld (compiler: GNU GCC Compiler) ===|
C:\Users\bartl\Documents\C++ Projects\HelloWorld\HelloWorld.cpp|1|warning: extra tokens at end of #include directive|
C:\Users\bartl\Documents\C++ Projects\HelloWorld\HelloWorld.cpp||In function 'int main()':|
C:\Users\bartl\Documents\C++ Projects\HelloWorld\HelloWorld.cpp|7|warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::basic_string<char>::size_type' {aka 'long long unsigned int'} [-Wsign-compare]|
C:\Users\bartl\Documents\C++ Projects\HelloWorld\HelloWorld.cpp|8|warning: comparison with string literal results in unspecified behavior [-Waddress]|
C:\Users\bartl\Documents\C++ Projects\HelloWorld\HelloWorld.cpp|8|error: ISO C++ forbids comparison between pointer and integer [-fpermissive]|
||=== Build failed: 1 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|

I'm doing it this way because I want to know the index the character appears at in the string and I want to find all instances of the character inside the string. How could I do this?

Aucun commentaire:

Enregistrer un commentaire