【问题标题】:C++: Unable to convert string to intC++:无法将字符串转换为 int
【发布时间】:2017-02-10 07:59:21
【问题描述】:

我正在尝试将两个字符串转换为整数,但我得到了

error: invalid cast from type 'std::basic_string<char>' to type 'int'

当我运行它时。这是代码。

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

class Instruction
{
private:
    vector<string> Inst;

public: 
    void readFile(string infile)
    {
        ifstream myfile (infile);
        if (myfile.is_open())
        {
            while (getline(myfile, line))
            {
                Inst.push_back(line);
            }
            myfile.close();
        }
        else
            cout << "Unable to open file." << endl;
    }

void runProcess()
    {
        for (int i=0; i<Inst.size(); i++)
        {
            op_code = getOperation(Inst[i]);

我将跳过 runProcess 的其余部分,因为它并不重要。在它下面,我有

    int getOperation(string inst)
    {
        return (int)inst.substr(2);
    }

这是我遇到麻烦的地方。我尝试过 (int)、stoi 和 atoi。没有任何效果。

我对 C++ 还很陌生,因此尝试从向量中传递字符串很可能是个问题,但我不确定。如果我需要发布其他任何内容,请告诉我。任何帮助将不胜感激。

【问题讨论】:

  • 使用stoi() 有什么问题?
  • 某些版本的 g++ 不支持std::stoi。见stackoverflow.com/questions/14743904/stdstoi-missing-in-g-4-7-2。但是,您应该可以使用std::atoireturn std::atoi(inst.substr(2).c_str());
  • @πάνταῥεῖ std::stoi() 给出了错误“stoi 不是 std 的成员”,而 std() 给出了“stoi 未在此范围内声明”
  • @RSahu std::atoi 也不起作用。相同的错误信息。我得检查一下我的编译器。
  • @cec526 : 你使用的是哪个版本的g++

标签: c++ string vector int type-conversion


【解决方案1】:

试试这个

#include <iostream>
#include <vector>
#include <sstream>

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

    std::vector<std::string> Inst;
    std::string line = "59";
    Inst.push_back(line);

    std::stringstream ss;
    int op_code;
    ss << Inst[0];
    ss >> op_code;
    std::cout << "op_code = " << op_code << std::endl;
    return 0;
}

它对我很有效。

但是,如果你说你的字符串包含 2 个字符,你为什么要写
inst.substr(2);?
这意味着您从索引 2 到末尾获取字符串中的数据。你确定这是你想做的吗?
如果您想要确保使用前 2 个字符,那么您应该改为写
inst.substr(0,2);

【讨论】:

    【解决方案2】:

    如果std::stoi不可用,建议使用strtol

    查看此问答了解详情:basics of strtol

    很快:

    const char *s = input.c_str();
    char *t;
    long l = strtol(s, &t, 10);
    if(s == t) {
       /* strtol failed */
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多