我想单独使用整数的数字,并在该数字前面打印n次数字n类似:
4:4444
3:333
到目前为止,我已经得到了这个,但它打印的是4:3,我不知道如何制作成我想要的:
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stack>
int countDigitsInInteger(int n)
{
int count =0;
while(n>0)
{
count++;
n=n/10;
}
return count;
}
using namespace std;
int main(int argc, char *argv[])
{
int intLength =0;
int number;
int digit;
string s;
cin >>number;
if (number<0)
number = -number;
intLength = countDigitsInInteger(number);
stack<int> digitstack;
while(number>0)
{
digit = number % 10;
number = number / 10;
digitstack.push(digit);
}
while(digitstack.size() > 0)
{
cout << digitstack.top() << ":"<< endl ;
digitstack.pop();
}
return EXIT_SUCCESS;
}
我也知道如何在一个单独的程序中写n次,但我不知道如何将这些代码组合成一个程序:
#include <iostream>
#include <string>
using namespace std;
void printNTimes(char c, int n)
{
cout << string(n, c) << endl;
}
int main()
{
int n = 6;
char c = 'G';
printNTimes(c, n);
return 0;
}
您可以使用std::to_string
将整数转换为std::string
,然后在该字符串中的char
上循环。
示例:
#include <iostream>
#include <string>
int main() {
int number = 43; // or read it from std::cin
std::string snumber = std::to_string(number);
for(auto ch : snumber) { // a range-based loop over the chars in snumber
std::cout << ch << ": "; // print the char
// loop the number of times that you want to print the char:
for(int count = ch - '0'; count; --count)
std::cout << ch; // print the char
std::cout << 'n';
// or:
//
// std::cout << std::string(ch - '0', ch) << 'n';
}
}
输出:
4: 4444
3: 333