Hi! I'm supposed to input a large integer value(long int) and output it like this:

input: 123456789
output: 123,456,789

I'm supposed to use recursion for this. I just need suggestions or partial codes - not a full code (I want to learn, not copy). I'm a newbie, and I don't know how to convert long int to strings. I'm not even sure we're supposed to do that yet. Please help. I don't know where to start.

7 Years
Discussion Span
Last Post by Duoas

>>I'm a newbie, and I don't know how to convert long int to strings.
Two methods:
1) In c++ use stringstream class

#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
   int n = 12345678;
   std::string s;
   std::stringstream str;
   str << n;
   str >> s;  // converts integer to string
   cout << s << "\n";

2) use sprintf()

#include <cstring>
#include <iostream>
using namespace std;
int main()
    char str[40];
    int n = 123456;
    sprintf(str,"%d", n);
    cout << str << "\n";

Alas, the OP want's to know how to insert those obnoxious commas (,) in between digits.

Remember to use integer division and modulo (remainder) to split numbers apart ( / and % ).
For example:

1492 % 10 --> 2
1492 / 10 --> 149

149 % 10 --> 9
149 / 10 --> 14


Then, to convert each digit you peel off into a number, just use the following kind of code:

int number = 7;
char digit = (char)number + '0';

Now think about how recursive functions work. In your case, you'll have to do three somethings, recurse, and then print stuff.

Hope this helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.