Please write in C++ programming. Write a function with the following prototype:
ID: 652955 • Letter: P
Question
Please write in C++ programming.
Write a function with the following prototype:
void middle_digits(const vector &inp, vector &outp);
where
inp will be an input vector of integers where each integer is an odd number in length
outp will be made up of the values of the middle digits of the corresponding integers in inp
Exampe if inp has the following values:
123 78923 3 123456789 8917564 then
outp will have the following values after function middle_digits is executed:
2 9 3 5 7
Write a main prgoram which:
declares an input vector of integers input_vec and and output vector of integers output_vec
asks the user to enter an integer which is odd number in legnth as input or a 'q' to stop entering input
calls the function middle_digits with input_vec and output_vec
prints out the values of the input vector input_vec
prints out the values of the output vector ouotput_vec
Please test with the data given above.
Explanation / Answer
#include <iostream>
#include <vector>
#include <stdlib.h>
#include<string.h>
#include <iomanip>
#include <locale>
#include <sstream>
using namespace std;
void middle_digits(const vector<int> &inp, vector<int> &outp){
int num;
int digit;
string strNum;
int strlength;
int mid;
int j;
for(int i=0;i<inp.size();i++){
strNum="";
num = inp[i];
ostringstream convert;
convert << num;
strNum = convert.str();
strlength=strNum.length();
mid=(strlength/2)+1;
j=1;
while(num>0){
if(j==mid){
outp.push_back(num%10);
}
num/=10;
j++;
}
}
cout<<" Output vector is: ";
for(int i=0;i<outp.size();i++){
cout<<outp[i]<<" ";
}
}
int main ()
{
vector<int> input_vec;
vector<int> output_vec;
char input[256]= "";
int num;
cout << "Please enter some integers with odd number length (enter Q or q to end): ";
do {
cin >> input;
if(input[0]=='Q'||input[0]=='q'){
break;
}
if(strlen(input)%2==0){
cout<<input<<" is not accepted. Enter number with odd number of digit ";
continue;
}
num=atoi (input);
input_vec.push_back (num);
} while (1);
cout << "myvector stores " << int(input_vec.size()) << " numbers. ";
middle_digits(input_vec,output_vec);
return 0;
}