Converting Binary to Decimal with functions

Hello all,

I am very new to C++ and I have a project due tomorrow in my C++ class and I'm rather stuck. I have to convert a binary value from an input file (the name of which is given by the user) and then convert the binary to decimal value and print that in an output file.

Right now it is compiling just fine with no error messages, but when I run the program, it doesn't end or print to the output file.

I know that this is last minute and late, but any ideas or help would be great and very much appreciated!!

Here is what I have at the moment:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  #include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

//function prototypes
char convertBinary (char);


int main()
{

ifstream fcin;
ofstream fcout;
char inputFileName[50]; //store file name entered by user
char ch; //single character to store user input
char outputFileName[50]; //store output file name
char output;

cout <<"Enter the input file name" << endl;
cin >> inputFileName; //read in user file name
cout <<"Enter file name where output is to be stored: " << endl;
cin >> outputFileName;

fcin.open("inputFileName"); // open the input file
fcin.get(ch); //read a character ch from the input file

fcout.open("outputFileName"); //open output file

char sum = convertBinary (ch);

fcout.setf(ios::left, ios::adjustfield);
fcout << setw (20) <<"Binary" << setw(20) << "Decimal"
<< setw (20) << ch << setw (20) << sum << endl;

fcin.close();
fcout.close();

return 0;
}

//functions

char convertBinary (char ch){

char bin1;
char bin2;
int sum= 0;

while(ch)
{
cin.ignore(10, ' ');
cin.get(bin1);
cin.get(bin2);
while(bin2 != '\n'|| ' ')
{
if (bin1 == '0')
sum = sum + 0;
else if (bin1 == '1')
sum = sum + 1;
else cout << "Bad digit on input.";
sum = sum * 2;
cout << bin1;
bin1 = bin2;
cin.get(bin2);
}
if (bin1 == '0'){
sum = sum + 0;
}
else if (bin1 == '1')
sum = sum + 1;

else cout << "Bad digit on input.";
cout << bin1 << " " << sum << endl;
return sum; 
}
}
When you say binary to decimal, do you mean like 1001 = 9?

I'm reading your convertBinary() function, and I don't understand why you use so many cin.get or cin.ignore?


Assuming you are trying to convert 1001 into 9...
Here's part of a binary converting thing I made a while back. I added some comments.

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
37
38
39
40
41
42
43

#include <iostream>
#include <string>

using namespace std;

int multiplyy(int x);

int main(){
	//binary stored in a string variable.
	string binary = "1001";
	
	//Binaries are calculated right to left, so 
	//by reversing, we can calculate left to right.
	//It makes calculation much easier.
	reverse(binary.begin(), binary.end());
	
	int sum = 0;
	
	int size = binary.size();

	//Goes through every element of the string.
	//If zero, nothing is done. If 1, then we multiply.
	for(int x = 0; x < size; x++)
		if (binary[x] == '1')
			sum = sum + multiplyy(x);

	cout << sum << endl;
	system("pause");
}

//Recursion function. So if x = 3, then the 
//function would compute 2^3, and return 8.
int multiplyy(int x){
	
	if (x == 0)
		return 1;
	if (x == 1)
		return 2;
	else
		return 2*multiplyy(x - 1);
}



Hope it helps.
Thanks! Helps me make more sense of it. I had the cin.get and such because I'm getting the strings from a file with multiple binary numbers in it like this:

1001
11011
01101

Then, after getting these inputs I have to convert, then output them to a new output file.
Oh, so there's more than 1 binary in the file, and the file is written like that?

You will definitely need a while-loop. You open the file correctly, but you only read the first line. And cin.get() does not read from the file. It just waits for the user to input something. In general, anything to do with cin means it's between the program and the user.

and make sure that the user inputs the .txt along with the file name. Like "filename.txt".
Try something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

ifstream in;
ifstream out;
string binary;//Holds the binary input from file.

in.open(inputname);

//Everytime the while loop runs, it reads one line. 
//So in your response above, this while loop will run 3 times.
while(!in.eof()){
     in >> binary;//So this takes the binary on the first line and stores it
//into the variable "binary". Conveniently, if you put my code in a function and  
// change it a bit, and pass it this "binary" variable, it will convert it to decimal.

....//do some other stuff

//and then you can output it to a file with something like this:

out << binary;
}



I THINK you can't have a ifstream and an ofstrem open at the same time. Not sure about that. If not, you can just store the binaries into an array of strings, and your answer into an array of decimals. And then output them after you calculate everything.

And to store the input into an array you could try something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

//declare an array of string:
string binaries[10];// 10 is just random number. 

//The amount of binaries goes there. 
//If there is 15 binaries in the file, it would be string binaries[15]; 

int count = 0;//This is the position of the array we will be writing to.

//.... and then right after the part where you write:
in >> binary;

//write this:
binaries[count] = binary;

count++;//to move to the next spot of the array.


It would be much easier using vectors instead of arrays, but arrays works.
Last edited on
Thanks for the suggestions, trying the (!fcin.eof()) part now. I honestly am spitballing a good chunk of this, as my professor has gone into depth on a lot of this. Went to her office hours the other day and she said "I didn't realize how complicated this was." (I'm in an entry level C++ class)

Just have to figure out how to run it all with functions.

Here is my code now after more tinkering:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/** 
 * binaryConvert.cpp
 * This program converts binary numbers into 
 *the equivalent decimal value.
 * <p>
 *
 * author: Jordan Warnecke
 * modified by: N/A
 * email: [email protected]
 * language: C++
 * pledge: I pledge. JHW 10/11/2013
 *
 */

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

//function prototypes
void convertBinary (char);


int main()
{

   ifstream fcin;
   ofstream fcout;
   char inputFileName[50]; //store file name entered by user
   char ch; //single character to store user input
   char outputFileName[50]; //store output file name
   //char output;
   string binary;
   
   while (!fcin.eof()){
      convertBinary (ch);
      }
    
fcin.close();
fcout.close();
    
return 0;
}

//functions

void convertBinary (char ch){
    
    ifstream fcin;
    ofstream fcout;
    char inputFileName[50]; //store file name entered by user
    //char ch; //single character to store user input
    char outputFileName[50]; //store output file name
    char bin1;
    char bin2;
    int sum= 0;
   
   
   cout <<"Enter the input file name" << endl;
   cin >> inputFileName; //read in user file name
   cout <<"Enter file name where output is to be stored: " << endl;
   cin >> outputFileName;

   fcin.open(inputFileName); // open the input file
   fcin.get(ch); //read a character ch from the input file
   
   fcout.open(outputFileName); //open output file
    
    while(!fcin.eof())
    {
          cin.ignore(10, ' ');
          cin.get(bin1);
          cin.get(bin2);
          while(bin2 != '\n'|| ' ')
          {
               if (bin1 == '0')
               sum = sum + 0;
               else if (bin1 == '1')
               sum = sum + 1;
               else cout << "Bad digit on input.";
               sum = sum * 2;
               cout << bin1;
               bin1 = bin2;
               cin.get(bin2);
          }
          if (bin1 == '0'){
          sum = sum + 0;
          }
          else if (bin1 == '1')
          sum = sum + 1;
          
          else cout << "Bad digit on input.";
          cout << bin1 << "                     " << sum << endl;
          
    
    fcout <<"Binary              Decimal"
          << ch << "                " << sum << endl;      
    }
}


Here is what I'm getting when I run the program:

1
2
3
4
Enter the input file name
Binary.txt
Enter file name where output is to be stored: 
binOutput.txt


The program continues to run without outputting anything to the output file. I feel like the function isn't getting called right?
Last edited on
Line 71, you have this:
while(!fcin.eof())
You are getting stuck in an infinite loop because apart from line 67, you don't read from the file, so if it wasn't eof on that first read, it will never reach the end of the file.

Remove line 67 fcin.get(ch); and line 71.

Merge them together like this:
1
2
3
4
    while (fcin.get(ch))  // read next char from fcin and check that it succeeded
    {
        // do something with the character ch
    }


Last edited on
Here is some code:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
#define STR(x) #x << '=' << x

static unsigned convertBinary(const string& str)
{
  unsigned result = 0;
  for (size_t i = 0; i < str.size(); ++i)  {
    if (str.at(i) == '0')
      result = 2 * result;
    else if (str.at(i) == '1')
      result = 2 * result + 1;
    else{
      cerr << "Bad digit on input." << endl;
    }
  }
  cout << STR(result) << endl;
  return result;
}

int main()
{
  char inputFileName[50]; //store file name entered by user
  cout <<"Enter the input file name" << endl;
  cin >> inputFileName; //read in user file name

  char outputFileName[50]; //store output file name
  cout <<"Enter file name where output is to be stored: " << endl;
  cin >> outputFileName;

  cout << STR(inputFileName) << ' ' << STR(outputFileName) << endl;

  ifstream fcin;
  fcin.open(inputFileName); // open the input file

  ofstream fcout;
  fcout.open(outputFileName); //open output file
  while (!fcin.eof()){
    string binary;
    fcin >> binary;
    cout << STR(binary) << endl;
    if (binary.size() == 0)
      continue; // ignore empty lines
    unsigned num = convertBinary (binary);
    cout << STR(num) << std::endl;
    fcout << num << endl;
  }
    
  fcin.close();
  fcout.close();
    
  return 0;
}


Remove
 
#define STR(x) #x << '=' << x 

and all lines that use this macro before submitting. They help you debug.

The
unsigned convertBinary(const string& str)
can possibly be improved on, but is easily understood.
Last edited on
Topic archived. No new replies allowed.