【问题标题】:Unable to resolve identifier stoi无法解析标识符 stoi
【发布时间】:2015-11-08 18:13:08
【问题描述】:

我正在尝试将字符串解析为整数,但我不确定自己做错了什么:

string input;
cin >> input;
int s = std::stoi(input);

这不会生成并引发错误:“stoi”不是“std”的成员。

【问题讨论】:

  • 尝试在 'cin' 语句的末尾添加分号。
  • 我这样做了,现在它说 'stoi' 不是 'std' 的成员。
  • 那么你需要包含 并确保告诉你的编译器使用 c++11(我相信 5.0 之前的所有版本的 gcc 都需要)。

标签: c++ std


【解决方案1】:

旧版本的 C++ 编译器不支持 stoi。对于旧版本,您可以使用以下代码 sn-p 将字符串转换为整数。

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

int main() {
    string input;
    cin >> input;
    int s = std::atoi(input.c_str());
    cout<<s<<endl;
    return 0;
}

否则使用高于 C++11 的 c++ 编译器版本。

【讨论】:

    【解决方案2】:

    您应该使用std::stringstream。 C 字符串实用程序对 std::strings 不利。

    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main() {
      int num1, num2;
      std::string line("5 6");
      std::stringstream ss(line);
      ss >> num1 >> num2;
      std::cout << "num1 is " << num1 << " and num2 is " << num2 << std::endl;
      return 0;
    }
    

    这是ideone

    【讨论】:

      【解决方案3】:

      您似乎忘记了包含字符串。

      除此之外,请记住 stoi 可能会抛出,因此您需要将其用法封装在 try/catch 块中,如下所示:

      using namespace std;
      try
      {
         string stringy= "25";
         int x= stoi(string);
         cout<<"y is: "<<y<<endl;
      }
      catch(invalid_argument& e)
      {
         cout<<"you entered something that does NOT evaluate to an int"<<endl;
      }
      

      试试这个,如果你给 stoi 提供说“x25”,它会抛出,如果没有它会通过。如果你不使用这种 try/catch 语法,程序将在 stoi 抛出的那一刻崩溃。

      此外,stoi 似乎足够聪明,可以在检测到未评估的内容时停止解析,因此“25x”可以正常工作,它会简单地省略 x。但是“x25”会抛出。

      虽然异常处理不是您问题的直接部分,但我认为提一下是明智的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-01
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        相关资源
        最近更新 更多