I'm a beginner to c++ and one of my homework assignments is to add two binary numbers located in a file. These numbers are separated by a space within the file. Assuming all binary numbers are 8-bits. So we read them from a file and store the 8-bits into a variable called byte that is a member each Byte object.
Ex)
10111010 11110000
11111111 00000000
Is this the correct way to write the coding for ignoring the white spaces?
int Byte::read(istream & file){
file.skipws;
file.get(byte, 8);
}
Or is this a better way?
int Byte::read(istream & file){
file.getline(byte, 8, ' ');
}
Thanks for any help. Apologizes if this was answered somewhere else. All I could find was examples that didn't involve files.
Skipping whitespace is enabled by default for text streams.
std::string num1, num2;
if (file >> num1 >> num2)
{
// use them
}
Since, apparently, you cannot use std::string:
#include <fstream>
std::istream& read8(std::istream& ifs, char(&arr)[8])
{
return ifs >> arr[0] >> arr[1] >> arr[2] >> arr[3] >> arr[4] >> arr[5] >> arr[6] >> arr[7];
}
int main()
{
std::ifstream file("input.txt");
char a[8], b[8];
while (read8(file, a) && read8(file, b))
{
// add a and b
}
}