I am trying to read a textfile, text.txt
with text representing hexadecimal values:
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
I am supposed to read this file and use ofstream
to write to a new file output.txt
to write the binary equiavalent of these hexademical values, with -
representing 0's and #
representing 1's.
Example:
0 = ----
1 = ---#
2 = --#-
...
F = ####
And my output for output.txt
is
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
when it should be
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
My logic is there, but it seems that output.txt
only writes the first line of text.txt
. This makes me believe that I am only reading the first line.
I am forced to use c-style strings, hence the char array I am reading into.
Here is my code
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("test.txt");
char words[10001] = {'\0'}; //c-style string
if (myfile.is_open())
{
while (!myfile.eof())
{
myfile >> words; //read myfile text into char words[]
ofstream outfile;
outfile.open("output.txt"); //ofstream to output.txt based on character in words[]
for (char c : words) //the ofstream to output.txt based on char c in words
{
if (c == '0')
outfile << "---#";
else if (c == '2')
outfile << "--#-";
else if (c == '3')
outfile << "--##";
else if (c == '4')
outfile << "-#--";
else if (c == '5')
outfile << "-#-#";
else if (c == '6')
outfile << "-##-";
else if (c == '7')
outfile << "-###";
else if (c == '8')
outfile << "#---";
else if (c == '9')
outfile << "#--#";
else if (c == 'a')
outfile << "#-#-";
else if (c == 'b')
outfile << "#-##";
else if (c == 'c')
outfile << "##--";
else if (c == 'd')
outfile << "##-#";
else if (c == 'e')
outfile << "###-";
else if (c == 'f')
outfile << "####";
}
}
myfile.close();
}
return 0;
}
I suspect it's the myfile >> words
, but I am not entirely sure. I added a few comments to try and explain the route I went.