repl.it
@tomnagel/

Text to binary converter

C++

No description

fork
loading
Files
  • main.cpp
  • binary_file
  • text_file
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream> //Used for files
#include <string> //Used for strings
std::fstream text_file ("text_file"); //assings the file to variable
std::fstream binary_file("binary_file");

void text_to_binary(std::string text){ //gets all text on line in text_file
  for (int pos_str = 0; pos_str < text.length(); ++pos_str){ //goes through all chars in text
    char bin_value = text.at(pos_str);//gets char from position in text
    for(int count{ 128 };count >= 1; count = count / 2){ //goes through the binary values of byte
      if(bin_value >= count){ // looks if char should get a 1 or a 0 
        binary_file << 1;
        bin_value = bin_value - count;  
      }
      else binary_file << 0; 
    }
    binary_file << " ";
  } 
}

int main(){
  if (text_file.is_open() and binary_file.is_open()){ //opens files and checks for error
    std::string text;
    while (getline (text_file, text) )//gets every line in text file
    {
        std::cout << text << '\n';
        text_to_binary(text); //calls function
        //binary_file << text <<"\n";
    }
    binary_file << "\n" <<"--New Text--" <<"\n";
    text_file.close(); //closes files after use 
    binary_file.close();
  }
  else std::cout << "Unable to open files";
  return 0;
}
Fetching token
?