功能stoi没有声明

use*_*512 21 c++ string int pointers

我正在尝试使用stoi将字符串转换为整数,但是它表示它没有声明.我有标准库和包含,但它仍然说"[错误]'stoi'未在此范围内声明"

代码如下:

#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;

}
Run Code Online (Sandbox Code Playgroud)

请告诉我它为什么不起作用,或者给我第二个选择.

Cap*_*ous 24

std::stoi是在C++ 11中引入的.确保您的编译器设置正确和/或您的编译器支持C++ 11.

  • @ user3258512,Express是免费的. (3认同)
  • DevC++是一个IDE而不是编译器.仔细检查随Dev C++副本提供的编译器版本,并在必要时进行升级,或添加所需的命令行开关以启用它. (2认同)

Eam*_*nny 17

上面的答案是正确的,但没有很好地解释.

g++ -std=c++11 my_cpp_code.cpp
Run Code Online (Sandbox Code Playgroud)

将-std = c ++ 11添加到您的编译器选项中,因为您很可能使用较旧版本的debian或ubuntu,默认情况下不使用g ++/gcc的新c ++ 11标准.我在Debian Wheezy遇到了同样的问题.

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

在绿色的右侧显示非常小的写入,需要c ++ 11.


nne*_*neo 10

stoi是一个C++ 11函数.如果您没有使用了解C++ 11的编译器,那么这根本就不会编译.

您可以使用a stringstream来读取输入:

stringstream ss(hours0);
ss >> hours;
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 9

stoi可用"自C++ 11以来".确保您的编译器是最新的.

您可以尝试atoi(hours0.c_str()).


小智 5

代替这条线-

int hours = stoi(hours0);

写这个-

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

参考: int atoi(con​​st char * str)