stoi() 在抛出 c++ 中的 'std::invalid argument in c++ 实例后终止 - 我做错了什么?
对编码相当陌生。在 LeetCode 上尝试一些简单的项目,但失败了……哈!我正在尝试获取一个整数并将其转换为字符串,以便我可以反转它,然后将反转的字符串重新转换回整数。
此代码抛出“抛出并实例'std::invalid argument'what(): stoi”错误。我花了一个小时在谷歌上搜索谷歌和其他问题,但不明白为什么它不起作用。
bool isPalindrome(int x) {
std::string backwards ="";
std::string NumString = std::to_string(x);
for (int i = NumString.size(); i >= 0 ; i--) {
backwards += NumString[i];
}
int check = std::stoi(backwards);
if (check == x) {
return true;
}
else {
return false;
}
}
编辑:我认为我已经弄清楚了。它在第一次转换时将空字符添加到字符串的末尾,然后在反转它时将其添加到字符串的开头。空格不能转换为整数。
所以...我改变了这一行并且它有效:
for (int i = NumString.size() - 1; i >= 0 ; i--)
Fairly new to coding. Trying some of the easy projects at LeetCode, and failing... Ha! I am trying to take an integer and convert it to a string so I can reverse it, then re-convert the reversed string back into a integer.
This code is throwing the "terminate after throwing and instance of 'std::invalid argument' what(): stoi" error. I've spent an hour searching google and other questions here on SO, but can't figure out why it's not working.
bool isPalindrome(int x) {
std::string backwards ="";
std::string NumString = std::to_string(x);
for (int i = NumString.size(); i >= 0 ; i--) {
backwards += NumString[i];
}
int check = std::stoi(backwards);
if (check == x) {
return true;
}
else {
return false;
}
}
EDIT: I think I figured it out. It was adding the null character to the end of the string upon first conversion, then adding it to the beginning of the string when I reversed it. Spaces can't be converted to integers.
So... I changed this line and it works:
for (int i = NumString.size() - 1; i >= 0 ; i--)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以在不使用字符串的情况下反转数字。
you can also reverse number without using string.
它比你编辑的答案更简单。你
想象一下 Numstring 的长度为 3 (无论空格、数字......)
所以现在你正在有效地做
所以第一个循环
顺利地在数组中的事物的索引C++中的长度3是0,1,2。你即将结束
这就是为什么你会看到循环
注意 i
i
i
i
i
i
i
i < len
不是i <= len
Its simpler than your answer that you edited in. YOu have
Imagine that Numstring has length 3 (no matter what spaces, digits,....)
So now you are efectively doing
So first loop goes
well the indexes of things in an array of length 3 in c++ are 0,1,2. YOu are going one off the end
This is why you see loops doing
Note the
i < len
noti <= len