jon*_*ark 4 c++ integer stringstream
我正在写一个函数来返回一个数字的反转,即它转换int(1234)为int(4321).这就是我目前所拥有的:
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
int reverse(int num) {
stringstream ss (stringstream::in | stringstream::out);
string initial;
int reversed;
// read the number in to a string stream
ss << num;
initial = ss.str();
// flush the stringstream
ss.str("");
for(unsigned int i(0); i <= initial.size(); i++) {
ss << initial[initial.size() - i];
}
ss >> reversed;
return reversed;
}
int main(int argc, const char *argv[])
{
int test = 9871;
cout << "test = " << test << endl;
cout << "reverse = " << reverse(test) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然而,这只是输出:
test = 9871
reverse = 0
Run Code Online (Sandbox Code Playgroud)
而且我非常肯定问题在于ss >> reversed问题reversed在于设置的问题0而不是价值ss,但是我无法弄清楚这个代码有什么问题,而且它真的很令人气愤,因为它似乎应该是简单.有人可以帮忙吗?
谢谢
i从0开始,然后initial.size() - i超出字符串边界.
改为1 ss << initial[initial.size() - i - 1];并i从1 迭代到initiali.size() - 1
for(unsigned i = 0; i != initial.size(); ++i) {
ss << initial[initial.size() - i -1];
}
Run Code Online (Sandbox Code Playgroud)
或者i从1 迭代到initial.size()
for(unsigned i = 1; i <= initial.size(); ++i) {
ss << initial[initial.size() - i];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1508 次 |
| 最近记录: |