-2

I'm trying to convert a two character string to an integer, but I get

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

when I run it. Here's the code.

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

I'll skip the rest of runProcess, as it is unimportant. Below it, I have

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

which is where I'm running into trouble. I've tried (int), stoi, and atoi. Nothing has worked.

I'm fairly new to C++, so it very well could be an issue with trying to pass in the string from a vector, but I'm not sure. If I need to post anything else let me know. Any help would be greatly appreciated.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
cec526
  • 1
  • 2

2 Answers2

0

If std::stoi is not available, it is recommended to use strtol.

Check this Q&A for details: basics of strtol

Shortly:

const char *s = input.c_str();
char *t;
long l = strtol(s, &t, 10);
if(s == t) {
   /* strtol failed */
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
0

Give this a try

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

It works well for me.

However if you say that your string contains 2 characters, why would you write
inst.substr(2);?
it means that you get the data in your string from index 2 till the end. Are you sure this is what you wanted to do?
If what you wanted is to make sure to take first 2 characters then you should write
inst.substr(0,2); instead.

iMadz
  • 41
  • 1
  • 7