I wrote a program to convert a string of 0 and 1's to char and write to a file and then read back from the file and output the corresponding string. It works fine but when I cout << the character read from the file, it looks different at the DOS prompt.
Here's the code:
int stringtoInt( string s)
{
unsignedint k = 0;
unsignedint p = 128;
for (int i = 0; i <s.length(); i++)
{
string s2 = s.substr(i,1);
if (s2.compare("1") == 0) //true, bit should be 1
{k = k | p;}
p = p/2;
}
return k;
}
void chartobitString( unsignedchar c)
{
string s;
unsignedint i = (unsignedint) c;
unsignedint p = 128;
for (int k = 0; k <8; k++)
{
if ((i & p) == p)
{
string s2 = "1";
s.append(s2);
}
else
{
string s2 = "0";
s.append(s2);
}
p = p/2;
}
cout << s <<endl;
}
int main (){
string s2 = "11010101";
cout<< (unsignedchar) stringtoInt(s2) <<endl;
ofstream myfile;
myfile.open("output.txt");
if (myfile.is_open())
{
unsignedchar c = ( unsignedchar) stringtoInt(s2);
myfile << c;
}
myfile.close();
ifstream myfile1;
myfile1.open("output.txt");
if (myfile1.is_open())
{
while (!myfile1.eof())
{
unsignedchar aa1 = myfile1.get();
cout<< aa1 <<endl; //this is different from the //file character !
chartobitString(aa1);
}
}
myfile1.close();
return 0;