Click here to Skip to main content
15,902,299 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I write a programme that removes the odd digits
but when I write 1001
it shows "all digits were deleted"
how should I change it?

What I have tried:

C++
#include <iostream>
using namespace std;
int main ()
{   
   long long int n;
   int digit,o=0,i=1;
   cin>>n;
   while( n != 0 )
   {
       digit = n % 10;
       n = n / 10;
       if( digit % 2 == 0 ) 
       {
           o += digit * i; 
           i *= 10; 	
       }
   }
   if(o=='\0')
       cout<<"All digits were deleted"<<"\n";
   else
       cout<<o<<"\n";
   return 0;
}
Posted
Updated 14-Nov-19 12:00pm
v2
Comments
ZurdoDev 14-Nov-19 14:03pm    
Debug it. Step through the code and figure out why it's not working. It's rude to ask someone else to do your homework for you.

Simple - if you remove all of the odd digits from 1001, you're left with 00.

And since you're treating the number as a number instead of a string, 00 is the same as 0. Which is the same as your "all digits were deleted" condition.

Read your homework assignment again. If zeros are significant in the output, then you'll need to turn the number into a string or an array of characters.
 
Share this answer
 
Comments
CPallini 14-Nov-19 16:23pm    
5.
Quote:
How should I change this programme?

Your error is that you handle input as a number.
Think of the problem as removing vowels from a string.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900