basically i just wanted to create a program which interchange a binary numbers after checking the number is binary. i was watched tutorial 22 from youtube channel named code with harry and he did similar type of code and i thought i will do on my own something like him but yet something diffrent
this is the code i wrote
#include <iostream>
#include <string>
using namespace std;
// A program to check binary number and interchange 0's and 1's
class binarychange{
string s;
public:
void read(void);
void chk_bin(void);
void change(void);
void display(void);
};
void binarychange :: read(void){
cout<<"enter a binary number"<<endl;
cin>>s;
}
void binarychange :: chk_bin(void){
for (int i = 0; i < s.length(); i )
{
if(s.at(i)!='0' && s.at(i)!='1'){
cout<<"Invalid binary format"<<endl;
}
}
}
void binarychange :: change(void){
for (int i = 0; i < s.length(); i )
{
if (s.at(i)==0)
{
s.at(i)=1;
}
else{
s.at(i)=0;
}
}
}
void binarychange :: display(void){
cout<<"Displaying your binary number"<<endl;
for (int i = 0; i < s.length(); i )
{
cout<<s.at(i);
}
cout<<endl;
}
int main(){
binarychange b;
b.read();
b.chk_bin();
b.display();
b.change();
b.display();
return 0;
}
the output i got
enter a binary number
101
Displaying your binary number
101
Displaying your binary number
the output i want
enter a binary number
101
Displaying your binary number
101
Displaying your binary number
010
CodePudding user response:
The value of s.at(i)
is a character, not an integer number, so you should test for s.at(i)=='0'
, rather than s.at(i)==0
in the binarychange :: change
method. Consequently, you should assign '1'
or '0'
instead of 1
or 0
, respectively.
CodePudding user response:
hey guys i got my answers, silly me just got hit by a small mistake
the correct code should be
#include <iostream>
#include <string>
using namespace std;
// A program to check binary number and interchange 0's and 1's
class binarychange{
string s;
public:
void read(void);
void chk_bin(void);
void change(void);
void display(void);
};
void binarychange :: read(void){
cout<<"enter a binary number"<<endl;
cin>>s;
}
void binarychange :: chk_bin(void){
for (int i = 0; i < s.length(); i )
{
if(s.at(i)!='0' && s.at(i)!='1'){
cout<<"Invalid binary format"<<endl;
exit(0);
}
}
}
void binarychange :: change(void){
for (int i = 0; i < s.length(); i )
{
if (s.at(i)=='0')
{
s.at(i)='1';
}
else{
s.at(i)='0';
}
}
}
void binarychange :: display(void){
cout<<"Displaying your binary number"<<endl;
for (int i = 0; i < s.length(); i )
{
cout<<s.at(i);
}
cout<<endl;
}
int main(){
binarychange b;
b.read();
b.chk_bin();
b.display();
b.change();
b.display();
return 0;
}