C++ 存储cout的值
我有以下代码C++ 存储cout的值,c++,for-loop,cout,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);
#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;
}
它能够输出我想要的值,但是有一个运行时故障2-变量“val”周围的堆栈已损坏。为什么会这样?您可以使用类似vector的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();
}
存储到vector,然后打印它 这并不难。因为你不知道结果的大小或数量,所以使用向量是很有用的 参考资料在这里
只需创建一个向量并返回您的结果,就可以不使用我们在@Wing Hang Khoo课程中没有学习过的代码。如何使用for循环将xx的值存储到变量中?我认为你应该放弃C++并接受jQuery。它内置了将值存储到变量中的for。谢谢,但不能使用我们在课堂上没有学过的代码。
#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();
}
#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