0

I'm new to C++, and since my first computer language is Python, I don't really understand what I did wrong here.

The purpose of this code is to find out how many certain alphabets are included in a string of length 8, but I keep getting the following error:

ISO C++ forbids comparison between pointer and integer [-fpermissive]

#include <iostream>

using namespace std;

int main() {
    int cnt = 0;
    string temp;
    cin >> temp; // the input string will be of length 8
    for (int i = 0; i < 8; i++) {
        if (temp[i] == "F") {
            cnt += 1;
        };
    };
    cout << cnt << endl;
    return 0;
}

When I print out temp[i] in the code, I can confirm that temp[i] is printed out as a single character, which I believe can be compared with another character, in this case the character "F".

I've been trying to find out why this is happening, but ended up coming here to ask for help.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
James
  • 31
  • 1
  • 2
  • 7

1 Answers1

1

if (temp[i] == "F") { should be if (temp[i] == 'F') {.

  • 'F' is a character (char)
  • "F" is a C-string (const char[2] which decays to const char*).
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Wow never thought C++ conceives "" and '' differently as they are literally the same in Python... – James Jan 29 '21 at 01:32
  • 1
    Different languages, so different conventions/rules. – Jarod42 Jan 29 '21 at 01:34
  • @James "*they are literally the same in Python*" - that is because Python doesn't have a dedicated single-character type, only a string type. So it can support both single-quote and double-quote syntaxes for string literals (many scripts languages do). C/C++, on the other hand, have separate types for single-characters and strings, so single-quote and double-quote are handled differently. – Remy Lebeau Jan 29 '21 at 01:43
  • @James: Notice that you can directly use `auto cnt = std::count(temp.begin(), temp.end(), 'F');` – Jarod42 Jan 29 '21 at 01:46