如何在不使用字符串的情况下将两个数字的数字存储在下面代码中的数组中



我需要一个程序来读取两个数字,并将这些数字存储在带有";"的数组中在他们之间。我尝试过使用char数组,但似乎对我不起作用,正如你下面看到的,我还尝试过先将数字存储在字符串中,然后放一个";"然后将它们存储在阵列中。没有绳子我怎么能做到?

#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b;
char v[99999];
string numTotal;
cin>>a>>b;
numTotal=to_string(a)+';'+to_string(b);
for(int i=0;i<numTotal.length();i++){
v[i]=numTotal[i];
cout<<v[i];
}
}

您可能想要使用一个名为getline(std::cin,(的函数(只要您不按特定的关键字,如:Enter或sth(,它会一次获取所有字符串(您可以写3;4或sth,它会逐字存储(。

getline(cin,numTotal);

字符串是最简单的方法,但如果您不想使用字符串,您可以使用类似的std::stack

int main() {
int a, b, n;
cin >> a >> b;
stack<int> aStack;
n = a;
while(n > 0) {
aStack.push(n % 10);
n /= 10;
}
stack<int> bStack;
n = b;
while(n > 0) {
bStack.push(n % 10);
n /= 10;
}
while(!aStack.empty()) {
cout << aStack.top() << ' ';
aStack.pop();
}
cout << 'n';
while(!bStack.empty()) {
cout << bStack.top() << ' ';
bStack.pop();
}
}

最新更新