Home > Software engineering >  no operator "<<" matches these operands recursive tower of hanoi error
no operator "<<" matches these operands recursive tower of hanoi error

Time:10-30

I'm new to c and working on a recursive towers of hanoi project. I have it completely done except for one small error. The second << in "cout << "Number of moves " << count; is giving me the error "no operator "<<" matches these operands". I understand it has something to do with count, but I am uncertain on how to fix it.

EDIT: There is also this error for the same line Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'overloaded-function'

CODE:

#pragma warning(disable: 4996) 
#include<string> 
#include<stdlib.h> 
#include<time.h>
#include<iostream>
#include<cmath>

using namespace std;

void toh(int p, char from, char to, char a){
    static int count = 0;
    if (p == 0) {
        return;
    } //if end

    if (p == 1) {
        cout << "from " << from << " to " << to << endl;
        count  ;
        return;
    } //if end

    toh(p - 1, from, a, to);
    cout << "from " << from << " to " << to << endl;
    count  ;
    toh(p - 1, a, to, from);
} //toh end

int main() {
    int num; bool t = 1;
    do {
        cout << "Enter the No. of the disks : ";
        cin >> num;
        cout << "source 1 target 2 temporary 3" << endl;
        toh(num, '1', '2', '3');
        cout << "2 to the " << num << " power = " << pow(2, num) << endl;
        cout << "Number of moves " << count;
        cout << "Continue? (1=yes 0=no) : ";
        cin >> t;
    } while (t);

    system("pause");
    return 0;
} //main end

CodePudding user response:

The variable count is defined local to the function toh, so you can return the count value which can be assigned to a variable called count inside main, allowing you to use it in the line cout << "Number of moves " << count;. It should look like this:

#include<stdlib.h> 
#include<time.h>
#include<iostream>
#include<cmath>

using namespace std;

static int toh(int p, char from, char to, char a){
    static int count = 0;
    if (p == 0) {
        return count;
    } //if end

    if (p == 1) {
        cout << "from " << from << " to " << to << endl;
        count  ;
        return count;
    } //if end

    toh(p - 1, from, a, to);
    cout << "from " << from << " to " << to << endl;
    count  ;
    toh(p - 1, a, to, from);
} //toh end

int main() {
    int num, count; bool t = 1;
    do {
        cout << "Enter the No. of the disks : ";
        cin >> num;
        cout << "source 1 target 2 temporary 3" << endl;
        count = toh(num, '1', '2', '3');
        cout << "2 to the " << num << " power = " << pow(2, num) << endl;
        cout << "Number of moves " << count;
        cout << "Continue? (1=yes 0=no) : ";
        cin >> t;
    } while (t);

    system("pause");
    return 0;
} //main end
  •  Tags:  
  • c
  • Related