Tłumaczenie tekstu na binarny

0

Witajcie nie wiem dlaczego program nie chce działać. Niby wypisuje kod 1 znaku, ale potem się buguje. Program ma za zadanie tłumaczyć znaki na binarny.

 #include <iostream>

using namespace std;

int main(){
	string wpisane;
	char aa;
	cin>>wpisane;
	int i=0,j=0,k=0,l=0;
	int tab[7];
	int z = wpisane.length();
	cout<<z<<endl;
	for(j=0;j<z;j++){
		
		aa = wpisane[j];
		
		while(aa!=0){
			tab[i]=aa%2;
			aa = aa/2;
			i++;
		}
		
		while(i<=8){
			tab[i]=0;
			i++;
		}
		
		for(l=7;l>=0;l--){
			cout<<tab[l];
		}
		
		i = 0;
		cout<<endl;
		
	}
}
0

Co chcesz osiągnąć?

0
for(l=7;l>=0;l--){
	  cout<<tab[l];

}

Powinno być

 for(l=6;l>=0;l--) {
    cout<<tab[l];
 }
0

Wyrzuć drugą pętlę "while", bo ona jest bez sensu i popraw pętlę for jak napisał kolega wyżej :)

0

Masz to samo tylko, napisane w lepszym stylu. Porównaj czytelność ze swoim kodem.

 #include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string decTobin(char c) {
  string result;
  while(c) {
    result += '0' + c % 2;
    c /= 2.0;
  }
  reverse(result.begin(), result.end());
  return result;
}

int main() {
  string text;
  cin >> text;
  for(int i = 0; i < text.size(); ++i) {
    char c = text[i];
    cout << decTobin(c) << '\n';
  }
  return 0;
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1