【问题标题】:C++ stoi out of scope issueC ++ stoi超出范围问题
【发布时间】:2016-05-15 23:11:41
【问题描述】:

我正在使用最新版本的 C++,并尝试运行以下代码。但是,它一直告诉我 stoi “未在此范围内声明”。我是 C++ 新手,所以如果您有任何想法,请分享。

#include <iostream>
using namespace std;

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



int main(int argc, char *argv[])
{

int a;
for (int i=0; i<argc; i++)
{
    string str(argv[1]);

    a=stoi(str);


   if (a<1) {
       cout<< "the sequence length must be greater than 1"<<endl;
   } else {
       cout <<"consecutive "<< a<<endl; // prints the input number of required consecutive
   }
}

int num[1000000];
int n, j;
n=1;

for (int x=1;!cin.eof() ; ++x)
{
    cin>>num[x];

    if (cin.fail())
    {
        cout<< "error, only integers allowed"<<endl;
    break;
    }


    else if (x>=a)

    {
        while ( num[x-n+1] - num[x-n] == 1)

        { ++n;

        if (n == a)
        { cout<< "sequence found: " ;

        for (j=a-1; j >=0; --j)

            cout<< num[x-j]<<" ";
        break;
        }
        }
    }
}

cout<<endl;
return 0;
}

【问题讨论】:

  • 哪个编译器以及如何编译(例如,命令)?
  • 我尝试运行此代码:ideone.com/AJcMA0,但它给出了不同的错误。你确定这是你得到的错误吗?
  • 我正在使用eclipse,只是构建了内置的构建工具@101010
  • 您使用stoi()而不是atoi()的任何原因?

标签: c++ string scope


【解决方案1】:

std::stoiC++11 及以上功能,因此在您的编译中启用 C++11。

在 gcc 或 clang 中,标志是-std=c++11

CXX -std=c++11 cc.cc

其中 CXX 将是 g++clang++

请在标题包含部分也进行此更改

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

【讨论】:

  • 更好的是,完全删除using namespace std;
  • 同意,在当前示例中节省了一些额外的输入:)
  • C++11 或更高版本是 GCC 5 IIRC(当然是主干)的默认值,因此您不在“最新的 C++”上 :)
  • 在 Windows 上获取 GCC > 4.8 很棘手。大多数搜索会将您带到 mingw。
猜你喜欢
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 2012-08-13
  • 2015-08-20
  • 2017-10-17
相关资源
最近更新 更多