存储cout的值

时间:2017-08-27 04:11:22

标签: c++ for-loop cout

我有以下代码

#include <iostream>
#include <math.h>
#include <string>
#include <sstream>
using namespace std;
int main() {
int value
cout << "Input your number: " << endl;
cin >> value;
string s = to_string(value);
const int count = s.length();
int position = count;
for (int i = 1; i < count + 1; i++)
{
    int pwr = pow(10, position - 1);
    cout << ((value / pwr) + position) % 10;
    position--;
    value = value % pwr;
}

如何使用for循环将((value / pwr) + position) % 10的值存储到变量中而不是cout。非常感谢您的帮助。

[编辑] 我添加了一个数组

int val[7];
int position = count;
for (int i = 1; i < count + 1; i++)
{
    int pwr = pow(10, position - 1);
    val[i-1] = ((value / pwr) + position) % 10;
    position--;
    value = value % pwr;
}
cout << "Encoded value is: ";
for (int i = 0; i < 8; i++)
{
    cout << val[i];
}

它能够输出我想要的值,但是存在运行时失败#2 - 变量'val'周围的堆栈已损坏。那是为什么?

2 个答案:

答案 0 :(得分:0)

您可以像使用矢量一样使用STL容器。

#include <iostream>
#include <math.h>
#include <string>
#include <sstream>
#include <vector>

using namespace std;
int main() {
  int value;
  cout << "Input your number: " << endl;
  cin >> value;
  string s = to_string(value);
  const int count = s.length();
  int position = count;

  vector<int> outputs;

  for (int i = 1; i < count + 1; i++)
  {
    int pwr = pow(10, position - 1);
    outputs.push_back(((value / pwr) + position) % 10);
    cout << outputs.back();

    position--;
    value = value % pwr;
  }

  cout << endl;

  // iterate through the vector later
  for (auto i : outputs)
  {
    cout << i;
  }

  cin.get();
}

答案 1 :(得分:0)

存储到矢量然后打印

它不是那么困难。由于你不知道大小是多少或者有多少结果,所以使用向量是有用的。

参考在这里http://en.cppreference.com/w/cpp/container/vector

#include <iostream>
#include <math.h>
#include <string>
#include <sstream>
#include<vector>
#include<iterator>
#include<algorithm>

using namespace std;

int main() {
    int value;
    vector<int> results;
    cout << "Input your number: " << endl;
    cin >> value;
    string s = to_string(value);
    const int count = s.length();
    int position = count;
    for (int i = 1; i < count + 1; i++)
    {
        int pwr = pow(10, position - 1);
        auto val = ((value / pwr) + position) % 10;
        results.push_back(val);
        position--;
        value = value % pwr;
    }
    copy(results.begin(),results.end(),ostream_iterator<int>(cout," "));

}

输出

Input your number: 
12
3 3 Program ended with exit code: 0