C++ stringstream >> int返回零

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,但是我无法弄清楚这个代码有什么问题,而且它真的很令人气愤,因为它似乎应该是简单.有人可以帮忙吗?

谢谢

Ale*_*ato 5

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)

  • 在不改变`for`中的终止条件的情况下,单独进行此更改仍会导致超出范围. (2认同)