DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Converting digits..need help! (http://www.daniweb.com/forums/thread167468.html)

winry Jan 10th, 2009 7:13 am
Converting digits..need help!
 
Hi everyone!I've started to learn C++ couple of months ago and having some trouble with the code i'm trying the write.. I have to write a function that converts every digit of the parameter to zero,except 2.And number of digits is unknown..
I made this but its's output is always 0.Even i enter a number that contains 2...I'll be glad if you could help..Thanks:)

#include<iostream>
using namespace std;


int convertNum(int n){

int digits=0;
int remainder;


for(int i=n;n!=0;n/=10)
digits=digits+1;

 


for(int j=1;j<=digits;j++){
n=n/10;
remainder=n%10;
if(remainder==2)
  remainder=2;
if(remainder!=2)
  remainder=0;

}

return remainder;

 
}

 

int main()
{
 int a;

 cout<<"Please enter a positive integer"<<endl;
 cin>>a;

cout<<"The converted version of "<<a<<" is ----> "<<convertNum(a);
 

return 0;
}

Salem Jan 10th, 2009 7:19 am
Re: Converting digits..need help!
 
I'd be glad if you could read all the intro threads which describe how to post code.

ddanbe Jan 10th, 2009 8:02 am
Re: Converting digits..need help!
 
What I could get out of your unformatted code was
if(remainder==2)
remainder=2;
if(remainder!=2)
remainder=0;
should be better :
if(remainder==2)
remainder=2;
leave this away-->if it IS 2 why set it to 2 ?
if(remainder!=2) remainder=0;-->+-OK, because if you want to print 2 it will print 0

da penguin Jan 10th, 2009 10:41 am
Re: Converting digits..need help!
 
Lines 11,12. n is 0 after them and also i don't get why u use for not while and why u need that int i

winry Jan 10th, 2009 11:14 am
Re: Converting digits..need help!
 
ok,thanks for your help..
i'll fix it..

zalezog Jan 10th, 2009 11:19 am
Re: Converting digits..need help!
 
You say that you don't know the exact number of digits.
Then why not he input to the function be a string
such that

string convertNum(string num)
{
 //1.set counter to 0
 //2.Check if it is the end of the string(using counter's position).
 // 3.if yes goto goto step 4
 //  else check if the character in the string is other than 2
//    if yes, fill  a zero in the string
//increment the counter
// goto step 2
//4.Display or return your string

}

Hope that i am not twisting the question.:twisted:

winry Jan 10th, 2009 1:31 pm
Re: Converting digits..need help!
 
Thank you so much zalezog..I've made it:)..I used string and it's way much easier...


All times are GMT -4. The time now is 8:46 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC