ssj3goku878
ssj3goku878

Reputation: 755

C++ read file and convert data

I am trying to make a program that will read a binary number written inside a text file and convert that binary number into another file but I can't figure out how to have the number already written in the "BinaryInputFile.txt" converted using a function I have. Code below

#include <iostream>
#include <bitset> 
#include <string>
#include <fstream>
#include <math.h>

int Binary(const char* binary);

using namespace std;

int main()
{
char* Num = "1010";
string line;



  ifstream myfile ("BinaryInputFile.txt");
    if (myfile.is_open()){

    while ( getline (myfile,line) ){
      cout << "Binary number read from the file is: " << line << '.\n'; // display line
     // printf("%d\n",Binary(line));

    }


    ofstream myfile ("BinaryConvert.txt");
        myfile << "Converted binary number is: " << '.\n';
        myfile.close(); //close file
  }
  else cout << "Unable to open file";




    return 0;
}


int Binary(const char* binary) //conversion
{
    int len,dec=0,i,exp;

    len = strlen(binary);
    exp = len-1;

    for(i=0;i<len;i++,exp--)
        dec += binary[i]=='1'?pow(2,exp):0;
    return dec;
}

Upvotes: 2

Views: 2552

Answers (1)

P0W
P0W

Reputation: 47854

If you've exactly one one binary number in "BinaryInputFile.txt" and no other character

You can use std::basic_string::c_str for your Binary function like following :-

myfile << "Converted binary number is: " << Binary( line.c_str() );

to write to your "BinaryConvert.txt"

Upvotes: 2

Related Questions