Write a program that does the following: Open a file \"numbers.txt\" read intege
ID: 3782302 • Letter: W
Question
Write a program that does the following:
Open a file "numbers.txt"
read integer numbers as strings from the file (one number per line)
convert each string to a numeric representation (without using stoi() or similar functions from the string library)
store converted numbers in an array
close "numbers.txt"
open a file "binary.txt"
convert each number in array to binary string representation (without using itoa(), sprintf(), or similar functions)
write binary string for number to file
close "binary.txt"
This is C++. Please read the requirements carefully.
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Function to convert a string to a number
// This basically go over a string and get
// value of each character as number (48 is ascii for '0')
int convertStoi(string str)
{
int num = 0;
for(int i = 0; i < str.size(); ++i) {
num = num*10 + (str[i] - 48);
}
return num;
}
// Function to reverse a string
void reverseStr(string &str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i=0; i<n/2; i++)
swap(str[i], str[n-i-1]);
}
// function to convert a number to a string representing its binary notation
// This is basically finding right most bit and then shifting it out by
// diving by 2 until no digit remain.
// This is initisally storing bits in reverse order and then reverse string
// to get actual binary representation.
string convertItob(int num)
{
int i =0;
string s = "";
while(num > 0)
{
int dig = num % 2;
num = num / 2;
char c = '0' + dig;
s += c;
}
reverseStr(s);
return s;
}
int main()
{
ifstream infile("numbers.txt");
string line;
int *numbers = new int[10000];
int i =0;
while (getline(infile, line))
{
int num = convertStoi(line);
numbers[i] = num;
i++;
}
infile.close();
ofstream outfile("binary.txt");
for(int j = 0; j < i; j++)
{
string bin = convertItob(numbers[j]);
outfile << bin << endl;
}
outfile.close();
return 0;
}
/*
Sample numbers.txt
1000
2999
5000
30000
output: binary.txt
1111101000
101110110111
1001110001000
111010100110000
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.