Function stoi not declared

171,087

Solution 1

std::stoi was introduced in C++11. Make sure your compiler settings are correct and/or your compiler supports C++11.

Solution 2

The answers above are correct, but not well explained.

g++ -std=c++11 my_cpp_code.cpp

Add -std=c++11 to your compiler options since you are most likely using an older version of debian or ubuntu which is not using by default the new c++11 standard of g++/gcc. I had the same problem on Debian Wheezy.

http://en.cppreference.com/w/cpp/string/basic_string/stol

shows in really small writing to the right in green that c++11 is required.

Solution 3

stoi is a C++11 function. If you aren't using a compiler that understands C++11, this simply won't compile.

You can use a stringstream instead to read the input:

stringstream ss(hours0);
ss >> hours;

Solution 4

stoi is available "since C++11". Make sure your compiler is up to date.

You can try atoi(hours0.c_str()) instead.

Solution 5

instead of this line -

int hours = stoi(hours0);

write this -

int hours = atoi(hours0.c_str());

Reference : int atoi(const char *str)

Share:
171,087
user3258512
Author by

user3258512

Newbie, however enthusiast programmer.

Updated on July 09, 2022

Comments

  • user3258512
    user3258512 almost 2 years

    I'm trying to use stoi to convert a string to an integer, however it says it's not declared. I have the standard library and the <string> included, but it still says [Error] 'stoi' was not declared in this scope

    The code is the following:

    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string>
    
    using namespace std;
    
    int main()
    {
    string end, init;
    cout << "Introduction" << endl;
    cout << "Start time (xx:yy)" << endl;
    cin >> init;
    string hours0 = init.substr(0,2);
    int hours = stoi(hours0);
    cout << hours << endl;
    system("pause");
    return 0;
    
    }
    

    Either tell me why it isn't working, or give me a second option to do it, please.