basic C++ question

Page 2 - Seeking answers? Join the AnandTech community: where nearly half-a-million members share solutions and discuss the latest tech.

yata

Senior member
Jun 2, 2000
746
0
0
Duckers
I had to tweak my code too. It may be the different compiler I'm using. I'm using the newest Metrowerks Codewarrior. ANSI/ISO standard just came out recently too. Don't know how up to date your Turbo C++ is.

Shoot. Here, take out the "size_t..." function proto line. And add another #include:

#include <string.h>


try this.



 

arcain

Senior member
Oct 9, 1999
932
0
0
Ok.. here we go.. this only taking in an integer (not a string) and not requiring anything else besides iostream.h. Depending on your compiler you may need to use &quot;#include <iostream.h>&quot; or change the namespace. Unchecked, should work, at worst .. err.. doesn't work. But the method is sound, and doesn't require anything special.

--

#include <iostream>

void recurseprint(int i)
{
if ( i == 0 )
return;
else {
recurseprint( i / 10 );
cout << i % 10 << endl;
}
}

int main()
{
int input;
cout << &quot;Enter an integer: &quot;;
cin >> input;
recurseprint(input);
return 0;
}
 

Duckers

Platinum Member
Mar 30, 2000
2,089
1
0
arcain;
your program works!
but it won't work with large numbers though!
I finally figured out how to get this to work; it took me several hours though :)
Here is the code I used:


#include <iostream.h>
int main()
{
long integer, digit;
long max = 1000000000;

cout<<&quot;Enter an integer: &quot;;
cin>>integer;

while (max > integer)
max = (max / 10);

while (max >=1){
digit = (integer / max);
cout<<digit<<endl;
integer = (integer % max);
max = (max / 10);
}
return (0);
}
 

arcain

Senior member
Oct 9, 1999
932
0
0
The only reason I could see it failing with large numbers is if the inputted values overflow the integer. On modern 32 bit systems, an integer and a long are both 32 bits, so you can enter a number up to 2^32. If you enter something larger, I'm not sure how cin will handle that. Glad to hear you were able to work it out. It only get harder.. but luckily it gets easier with practice :)