【发布时间】:2022-01-09 04:11:23
【问题描述】:
基本上我只是想创建一个程序,在检查数字是二进制后交换二进制数。 我和 harry 一起从 youtube 频道观看了名为 code 的教程 22,他做了类似类型的代码,我想我会像他一样自己做一些事情,但有些不同
这是我写的代码
#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;
}
我得到的输出
enter a binary number
101
Displaying your binary number
101
Displaying your binary number
我想要的输出
enter a binary number
101
Displaying your binary number
101
Displaying your binary number
010
【问题讨论】:
-
这并没有解决问题,但是在这两个
for循环中,您知道i是字符串的有效索引,因为您编写了它这样,您就无需使用s.at(i)进行检查。只需使用索引运算符:s[i]。