1

I have fixed it another way but I still want to know why stoi is not working here. This is the code:

#include <string>
#include<iostream>
std::string fakeBin(std::string str){
    for(int i=0;i<str.size();i++){
        int number=stoi(str[i]);
        std::cout<<number<<std::endl;
    }
    return "a";
}
int main()
{
fakeBin("12354234");
return 0;
}

while compiling

int number=stoi(str[I]);

I get this error:

'stoi' was not declared in this scope

Can you explain me why I am getting this error?

Martin
  • 3,396
  • 5
  • 41
  • 67
Raihan_Alam
  • 89
  • 2
  • 10

3 Answers3

1

std::stoi function takes std::string as parameter. I suppose the question arises why the following code works but not yours.

std::string s = "1";
int i = stoi(s);

The above code compiles fine without std:: prefix because of argument-dependent lookup (ADL). Basically, if a parameter is in a namespace, function resolution will be performed in that namespace as well. In this case, string is in std namespace.

In your case, however, the provided parameter is a char reference. Since no parameter is in a namespace, function resolution occurs only on global scope, thus it fails.

Function resolution succeeds when std::stoi is explicitly provided. In that case, an std::string is implicitly constructed from the char reference, and given as the first parameter to stoi.

Note that being able to avoid typing the namespace of a function with the help of ADL does not necessarily mean you should do that way. Explicitly typing the namespace prevents such issues. If nothing else, it informs the future reader about the origins of a function.

Burak
  • 2,251
  • 1
  • 16
  • 33
0

You should write std:: stoi or you can add a line " using namespace std; " just after the headerfile.

There are another mistake : stoi work only strings .here str[i] is a character . so you have to create a empty string variable string s=""; and then s= s+ str[i] ; after this you can do std:: stoi(s);

  • [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/995714) – phuclv Jan 26 '22 at 02:47
0

use std:: before stoi (std::stoi)

std::stoi arguments are not true, so you are not using correct syntax, try to fix it as follows:

int       stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
int       stoi( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 );

and at least use c++11

Pouya
  • 1
  • 1