Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help with this progamming assignment in c++ 1. Open a file \"numbers.txt\"

ID: 3781449 • Letter: N

Question

Need help with this progamming assignment in c++

1. Open a file "numbers.txt"

2. read integer numbers as strings from the file (one number per line)

3. convert each string to a numeric representation (without using stoi() or similar functions from the string library)

4. store converted numbers in an array

5. close "numbers.txt"

6. open a file "binary.txt"

7. convert each number in array to binary string representation (without using itoa(), sprintf(), or similar functions)

8. write binary string for number to file

9. close "binary.txt

has to be done in c++ thanks

Explanation / Answer

//rate my answer if you like,thanks

#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
//for reverse of string function
#include <algorithm>
//define MAX to declare number of maximum array elements
#define MAX 100
using namespace std;

int strToNumber(string s);
//char *numberToStr(int num);
//char *reverseStr(char *s);
string numberToStr(int num);
int main()
{
   //declare in and out stream object to read and write to file
   ifstream in;
   ofstream out;
   //declare array to store numbers
   int numbers[MAX];
   string s;
   int count = 0;

   in.open("numbers.txt");
   out.open("binary.txt");

   //check if file can be open for reading
   if (!in)
   {
       cout << "File can't be opened for reading" << endl;
       return -1;
   }
   //read numbers as string from numbers.txt and convert each string to number and store in array
   while (!in.eof())
   {
       in >> s;
       numbers[count++] = strToNumber(s);
   }

   //check if binary.txt can be opened for writing
   if (!out)
   {
       cout << "File can't be opened for writing" << endl;
       return -1;
   }
   //write array of number as string to binary.txt
  
   for (int i = 0; i < count; i++)
   {
       s = numberToStr(numbers[i]);
       out << s << endl;
   }

   in.close();
   out.close();
}


int strToNumber(string s)
{
   int num=0;
   for (int i = s.length()-1, j = 0 ; i >=0 ; i--,j++)
   {
       num += (s[j]-48) * pow(10, i);
   }
   return num;

}

string numberToStr(int num)
{
   string str;
   int i = 0;
   do
   {
       str+= num % 10 + 48;
   } while (num = num / 10);

   reverse(str.begin(),str.end());

   return str;

}

----------------------------------------------------------------------------------------

numbers.txt

127
8976
45
5

binary.txt

127
8976
45
5