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.
In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings.
std::stoi is a standard library function, not a keyword. A keyword is something like for or new .
To do this, click on Tools in Dev-C++ IDE. Under this click the “Settings” tab. Inside the settings tab, we can see the “Code generation” tab. Click on the “Language Standard (-std)” value and set it to “ISOC++11” or “GNUC++11” as per your requirement.
Using atoi() First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.
std::stoi
was introduced in C++11. Make sure your compiler settings are correct and/or your compiler supports C++11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With