简体   繁体   中英

“error: invalid operands of types 'int' and 'const char [2]' to binary 'operator<<'|”

First of all, i'm a beginner. I've seen similar issues through the web with the same error as me, but none of then were quite like mine therefore i wasn't able to understand what i am doing wrong.

I'm supposed to make a fibonacci sequence shows up to the number i choose (as a portuguese speaker, i must explain, "primeiro" means first, "segundo" second and "terceiro" third.) The code is like this

#include <iostream>
using namespace std;
int main(){
int n;
int primeiro, segundo, terceiro;

primeiro = 1;
segundo = 1;
cout << "Insira o Valor Limite: ";
cin >> n;
cout << " " << endl;

while(terceiro < n){

    cout << primeiro << " " ;
    cout << segundo << " " ;
    terceiro = primeiro + segundo;
    cout << terceiro << " " ;

    primeiro = segundo << " ";
    segundo = terceiro << " " ;
    cout << " " << endl;

}

return 0;
}

the error appears on both of the following lines

primeiro = segundo << " ";
segundo = terceiro << " ";

and is like this

"error: invalid operands of types 'int' and 'const char [2]' to binary 'operator<<'|"

Please Help

Well what are you trying to actually do in those two lines? Seems to me that you'll probably want to set the 'primeiro' and 'segundo' variables to new values and continue looping. So there's no need for the "<<" operator. Change those two lines to

primeiro = segundo;
segundo = terceiro;

Also you'll need to initialise terceiro to some value...

To get this to work the two lines indicated should be

primeiro = segundo;
segundo = terceiro;

The issue here is that the << operator is overloaded. In addition to being an operator that takes and returns a stream it is also a bit shift operator. Eg 1 << 2; would take the binary representation of 1 ( 00000001 ) and shift it bits two places to the left ( 00000100 ), making it 4. What you are doing is that you are trying to bit shift the integers primeiro and sedgundo to the left with a string which results in a type error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM