0

I'm trying to get user input for two arrays. I'm getting the error no operator matches these operands. Why isn't my cin function working?

#include <iostream>
using namespace std;
int main()
{
    string canadates[5];
    int votes[5];
    double percent[5];
    int i;
    while (i <= 5) {
        cin<< canadates << votes;
    }
}

1 Answers1

6

There's quite a few issues with your code.

First, cin uses different operator than cout.

cin >> canadates >> votes;

Second, also part of the compiler error - you cannot read into whole array. You need into read into single element of an array. How do you access single array element?

cin >> canadates[i] >> votes[i];

Third, your loop is infinite one, because i never changes.

while (i <= 5) {
    cin >> canadates[i] >> votes[i];
    i++;
}

Fourth, i is unitialized - it has indeterminate value. Always initialize your variables.

int i = 0;
while (i <= 5) {
    cin >> canadates[i] >> votes[i];
    i++;
}

Fifth, arrays in C++ use zero-based indexing, which means first possible index is 0 and last possible index is arraySize - 1. Accessing element 5 in array of 5 elements is wrong.

int i = 0;
while (i < 5) {
    cin >> canadates[i] >> votes[i];
    i++;
}

Points 3 and 4 are much easier to avoid if you use for loop. It's syntax makes you remember about all those little things.

for(int i = 0; i < 5; i++) {
    cin >> canadates[i] >> votes[i];
}

See? Both issues solved in one line, and you need 3 statements there, compiler will check that (but compiler will not prevent you from shooting your own foot - each of the 3 statements may be empty, or you may still use them wrongly). And if you make a mental rule that i <= something is highly suspicious, you can also avoid 5th easier.


I don't want to discourage you from programming, but C++ is a difficult language. You will not be able to learn it without a good book/tutor, and in particular the fact that "code looks reasonable" or "code compiles" means nothing here.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52