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

use c++ Write a function GetAmounts..) that is given a string, an array to fill

ID: 3590449 • Letter: U

Question

use c++

Write a function GetAmounts..) that is given a string, an array to fill and the max number of elements in the array as parameters and returns an integer result. The function will separate each substring of the given string between space characters and place it in the array.. The function returns the number of values extracted. For example: GetAmounts("1.23 4.56 7.89", float valuesD, int max_values) would return the count of 3 and fill the array with floating point values 1.23, 4.56, 7.89.

Explanation / Answer

#include <string>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

int GetAmounts(string str, float *arr, int max_values){
vector<string> floatNums;
int pos = str.find(' ', 0);
int initPos = 0;
//Extract floats by finding spaces, stop when reached end of string
while(pos != string::npos){
//currentFloat contains string representation of float extracted
string currentFloat = str.substr(initPos, pos - initPos);
//floatNums vector contains all floats in string representation
floatNums.push_back(currentFloat);
//update initPos to start search of next space from updated position
initPos = pos+1;
pos = str.find(' ',initPos);
}
//To store the last float in the string
floatNums.push_back(str.substr(initPos));
int values = 0;
for(int i=0; i<max_values; i++){
//atof() converts a c-style string to a float
arr[i] = atof(floatNums[i].c_str());
values++;
}
return values;
}

int main() {
string str = "1.23123 444.56 0.89";
float arr[3];
int values = GetAmounts(str, arr, 3);
for(int i=0; i<3;i++){
cout<<arr[i]<<" ";
}
return 0;
}