c++ - 在创建堆栈数据结构时使用 stoi 会导致错误
问题描述
我已经创建了一个堆栈数据结构并正在实现它。我一直在使用下面的功能,
void Stack::solution(const char *input_path, const char *output_path)
{
string line;
Stack tempStack;
ifstream myfile(input_path);
ofstream outfile(output_path);
while (getline(myfile, line)) {
if (line.substr(0,1) == "s") {
Stack tempStack = Stack();
};
if (line.substr(0,1) == "e") {
int a = stoi(line.substr(1,1));
tempStack.push(a);
};
if (line.substr(0,1) == "o") {
int a = stoi(line.substr(1,1));
int num = tempStack.pop();
string x = to_string(num);
outfile << x << "";
};
}
}
但问题是这部分代码,除非不是:
if (line.substr(0,1) == "o") {
int a = stoi(line.substr(1,1));
int num = tempStack.pop();
string x = to_string(num);
outfile << x << "";
};
我收到此错误:
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
Abort trap: 6
我最初认为问题在于我没有将 a 转换int num
为 a string
,但即使我有,该错误也没有更接近解决。
解决方案
您没有显示您的输入的实际外观,但如果它与此问题中显示的输入类似,则o
案例没有与之关联的整数值,因此调用line.substr(1,1)
不会返回string
可以std::stoi()
转换为int
,因此为什么std::invalid_argument
会抛出异常。这是有道理的,因为这种o
情况意味着只从堆栈中弹出一个值,而不是将新值压入堆栈。因此,只需std::stoi()
完全删除对:
if (line.substr(0,1) == "o") {
//int a = stoi(line.substr(1,1)); // <-- get rid of this!
int num = tempStack.pop();
string x = to_string(num);
outfile << x;
};
此外,您tempStack
在机箱内有 2 个对象s
。您正在创建一个遮蔽现有对象的第二个Stack
对象,这不是您想要发生的。这段代码:Stack
Stack tempStack;
...
if (line.substr(0,1) == "s") {
Stack tempStack = Stack();
};
应该是这样的:
Stack tempStack;
...
if (line.substr(0,1) == "s") {
tempStack = Stack();
};
因此,话虽如此,您的函数应该看起来更像这样:
void Stack::solution(const char *input_path, const char *output_path)
{
string line;
Stack tempStack;
ifstream myfile(input_path);
ofstream outfile(output_path);
while (getline(myfile, line)) {
if (line.substr(0,1) == "s") {
tempStack = Stack();
}
if (line.substr(0,1) == "e") {
int a = stoi(line.substr(1,1));
tempStack.push(a);
}
if (line.substr(0,1) == "o") {
int num = tempStack.pop();
string x = to_string(num);
outfile << x;
}
}
}
推荐阅读
- c - 我试图将一个字符串解析为不同的单词,稍后尝试释放它们,但其中 2 个字符串具有相同的字节地址
- python-3.x - 如何从 python 代码中调用系统来传输 python 创建文件的数据?
- linux - 脚本在 crontab 中不起作用,但在终端中起作用
- html - CSS 背景图片仅在 Chrome 中有效,在其他浏览器中无效
- python-3.x - 在 ubuntu 中生成 .aln 文件时在谷歌平台上运行 clustalw 时出错
- jquery - 当 ajax 请求完成或失败时,Ajax 微调器不隐藏
- json - 使用 Hibernate-GORM 时,如何将域类转换为 JSON 字符串?
- shell - linux shell中删除100M大文件前N行的有效方法
- java - 无法通过 AsyncTask 和 inputStreamReader 获取 HTML 代码
- python - 在 smtplib 中设置超时