【发布时间】: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::atoi。return std::atoi(inst.substr(2).c_str()); -
@πάνταῥεῖ std::stoi() 给出了错误“stoi 不是 std 的成员”,而 std() 给出了“stoi 未在此范围内声明”
-
@RSahu std::atoi 也不起作用。相同的错误信息。我得检查一下我的编译器。
-
@cec526 : 你使用的是哪个版本的
g++?
标签: c++ string vector int type-conversion