Read input from file (characters) and store them as a binary array in C++. Input
ID: 3853419 • Letter: R
Question
Read input from file (characters) and store them as a binary array in C++.
Input file will be mixed between characters and numbers, so I cannot read the entire file in as a binary file. ONLY NEED THE CHARACTERS AS BINARY.
File input will be something like this:
2
HELLO
3
232
And as I stated above, i only need the characters (in this case, 'HELLO') read in and stored as binary. I've trying using <bitset> but I will need to modify the binary information later on in the program, so maybe an array or vecotr of chars?
Explanation / Answer
Following steps can be followed:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <string.h>
#include <cctype>
using namespace std;
bool isNumber(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
int main()
{
string line;
ifstream infile("input.txt");
ofstream outfile("output.txt", ios::binary|ios::out);//, ios::binary);
while(getline(infile, line))
{
if (isNumber(line) == true)
{
line = line + " ";
outfile.write(line.c_str(), line.length());
}
}
infile.close();
outfile.close();
cout << "Integers from input file have been written to output file as binary" << endl;
return 0;
}
OUTPUT:
$ g++ program.cpp
$ ./a.out
Integers from input file have been written to output file as binary
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.