AKuro
AKuro

Reputation: 79

c++ to_string was not declared in this scope error [Windows + Devcpp environment]

I am trying to implement the Karatsuba multiplication algorithm in c++ on Windows 10 using Devcpp ide. Here is the code for the same:

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int karatsuba(int x, int y){
    string sx = to_string(x);
    string sy = to_string(y);
    int len_x = strlen(sx);
    int len_y = strlen(sy);
    if (len_x == 1 && len_y == 1)
        return x * y;
    else{
        int n = max(len_x, len_y);
        int n_by_2 = n / 2;

        int a = x / pow(10, n_by_2);
        int b = x % pow(10, n_by_2);
        int c = y / pow(10, n_by_2);
        int d = y % pow(10, n_by_2);

        int ac = karatsuba(a, c);
        int bd = karatsuba(b, d);

        int ad_plus_bc = karatsuba(a+b, c+d);
        int prod = ac * pow(10, n_by_2) + (ad_plus_bc * pow(10, n_by_2)) + bd;
        return prod;
    }
}

int main(){
    cout<<karatsuba(45, 45);
}

When I run this program I get these errors:

C:\Users\AKuro\Desktop\C++\Divide and Conquer\karatsuba.cpp In function 'int karatsuba(int, int)': 7 25 C:\Users\AKuro\Desktop\C++\Divide and Conquer\karatsuba.cpp [Error] 'to_string' was not declared in this scope

9 23 C:\Users\AKuro\Desktop\C++\Divide and Conquer\karatsuba.cpp [Error] 'strlen' was not declared in this scope

18 29 C:\Users\AKuro\Desktop\C++\Divide and Conquer\karatsuba.cpp [Error] invalid operands of types 'int' and '__gnu_cxx::__promote_2::__type {aka double}' to binary 'operator%'

20 29 C:\Users\AKuro\Desktop\C++\Divide and Conquer\karatsuba.cpp [Error] invalid operands of types 'int' and '__gnu_cxx::__promote_2::__type {aka double}' to binary 'operator%'

I tried the methods I found through Googling but none of them seem to work. Here is what I have already tried:

using std with to_string as such std::to_string

I have even tried this approach

int i = 1212;
stringstream ss;
ss << i;
string s=ss.str();

but none seems to work and I couldn't find any answer to this particular environment (Windows 10 + Devcpp). It has been really bugging me. Please if you could help me out.

Upvotes: 0

Views: 4977

Answers (1)

mahesh
mahesh

Reputation: 1098

There are multiple errors here:

1) to_string() is a c++11 feature. So make sure you set -std=c++11 in your makefile or IDE.

2) strlen() is declared in cstring, not string. Better way here is to use something like int len_x = sx.size();, and similar for the other string.

3) Return type of pow() is float or double. So you need to cast it expicitly like this: int b = x % static_cast<int>(pow(10, n_by_2));. You need to do this for all expressions which use pow() and assign result to int variable. Actually, even better than casting would be to write your own simple intpow() function, which is not hard to do (it is so simple that the standard seems to have skipped it :-) ).

Upvotes: 1

Related Questions