-
conversion
Hello all I was just wondering if there is a good way to change the output of something from a char to an int observe the following code.
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
ofstream outfile("lengthindicator.txt");
class lengthindi
{
private:
char buffer[59];
char lengthindbuff[55];
short lengthindicator[4];
char blankline[80];
public:
lengthindi()
{
int k=0;
while(k<79)
{
blankline[k]=32;
++k;
}
}
friend ostream& operator <<(ostream &stream, lengthindi &p)
{
int i=0;
outfile<<p.lengthindbuff<<endl;
cout<<p.lengthindbuff<<endl;
strcpy(p.lengthindbuff, p.blankline);
strcpy(p.buffer, p.blankline);
return stream;
}
friend istream& operator >>(istream &stream, lengthindi &p)
{
int i=0;
int j=0;
int k=0;
short len;
char delim='|';
stream.getline(p.buffer, 58, '\n');
len=strlen(p.buffer);
if(len==0) return stream;
else
p.lengthindbuff[i]= len;
++i;
while(j <= len)
{
p.lengthindbuff[i]=p.buffer[j];
++i;
++j;
}
while(i<53)
{
p.lengthindbuff[i]=p.blankline[i];
++i;
}
cout << p; //overload the cout operator to send to output file
return stream;
}
};
void main()
{
lengthindi t;
fstream infile;
infile.open("delimeter.txt", ios::in);
while(!infile.eof())
{
infile >> t;
}
infile.close();
}
the problem I'm having is the variable "len" is appering as the ascii equivalent rather than the number. I need to change it to a number that can be recognized right away
-
You can type cast the variable to an int or just save it to an integer variable for example.
Code:
(int)charvariable
int iVar = cVar;
The only problem with that is when the char is representing the number 255 meaning that all the bits are 1. So when the variable is converted the sign bit will be propagated turning the int value into a negative one instead of the correct 255. That is an easy fix and I will let you figure out how to solve that one.