making number repeater program

Mar 5, 2010 at 5:27pm
hey guys i've been trying so far to make a "number repeating" program in c++.
for example i "cin" the number 12 and i want the output to be 12121212
input:8
output:88888888
input:123
output:12312312
lenght must be 8 digit number
please help me
Mar 5, 2010 at 7:01pm
What do you have so far?
Mar 6, 2010 at 8:14am
nothing special
Mar 8, 2010 at 2:38am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{
while(true)
     {
     int Number;
     cout << "enter a number to repeat.\n";
     cin >> Number;
     for(int PrintEight = 0;PrintEight < 8;PrintEight++)
        {
        cout << Number;         
        }      
     cout << endl;
     }
return 0;
}



there you go it took a whole 2 minutes to make.
Mar 8, 2010 at 3:18am
You are NOT supposed to just post the answer. Ever.
Mar 8, 2010 at 3:26am
That doesn't appear to be the final answer anyway. It looks tricky, as the number of digits of output is always 8, not the number of times the entered number is output.
Mar 8, 2010 at 3:31am
True.
@OP: Try getting a string instead of an integer. Then, you can go through the string 8 times, printing out the current counter % digit count index character. Sorry if that's really confusing, I'll give you a code snippet:
1
2
3
4
for (int x = 0; x < 8; x++)
{
    cout << somestring[x % somestring.length());
}

I don't actually remember what the member is that a string uses to return its length (shameful I know) but that should work OK.
Note that the above example will not work with numbers that are more than 8 digits long, I think. (Is 8 % numbergreaterthan8 going to evaluate to 8 or zero? I really don't remember)
Last edited on Mar 8, 2010 at 3:33am
Mar 9, 2010 at 5:31pm
@tummychow is that a rule here or somthing? cause i dident see it.

@moorecm now i see what you mean total length has to be 8 digits not same number 8 times. but that would still be easy,I could post it but idk if its against the rules(according to tummychow it is). if someone could post and let me know if it is or isn't. if it isn't against the rules i will post the correct answer.
Mar 9, 2010 at 6:14pm
It's more like a guideline... Personally, I do whatever I feel elicits the most learning from the OP--this could range from pleading the 5th to posting an entire program's source code. Most often, a probing question or two and possibly a small snippet do the trick.
Mar 9, 2010 at 6:26pm
Hi

I would use an ostringstream, append with "<< n" as long as the string length is lower than 8 and cout the resulting string with erase(8).

I hope its not too much of solving the excercise, since you still need to code it.

If it is possible to do more elegant, i am open for more ideas.
First I thought to use snprintf or strncat or something like this from <cstring>. But i think it is safer to do it with string objects.

Greatings, Maikel
Topic archived. No new replies allowed.