Read floats into a 2 dimensional array Part 2 - Read floats into 2 dimensional a
ID: 3597294 • Letter: R
Question
Read floats into a 2 dimensional array
Part 2 - Read floats into 2 dimensional array In this part, you will read a file with floating point values separated by commas and store them in an array int fillArray(string filename, float array [] [5]) The fil1Array function takes in two arguments: the filename and a float two dimensional array that can hold 5 floats in each row. Your function should fill the array with the values from the file, and return the total number of lines of the file, excluding the header line The input file will look like this. The first line is a header line that describes the columns of data in the file. This line must be ignored when reading the data Assignmentl, A2, A3, A4, A5 90.2, 80, 0, 75.4, 98. 2 94, 93.5, 92, 88, 87.5 80.2, 76, 88.2, 90.1, 82 For the above input, you should get an array like this 90.2 94 80.2 80 93.5 76 75.4 98.2 87.5 82 92 88.2 90.1Explanation / Answer
The above mentioned problem is coded in c++.
Below is the function fillArray() that read from a file and fills the 2D array with the float values and return the number of line.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>
using namespace std;
int fillArray(string filename, float array[][5]) {
std::ifstream file(filename);
std::string line;
bool firstLine = true;
int numberOfLines = 0;
// Read a line of input from the file
while (std::getline(file, line))
{ // ignore the first line
if (!firstLine)
{
// replace commas with blank space
std::replace(line.begin(), line.end(), ',', ' ');
// `istringstream` behaves like a normal input stream
// but can be initialized from a string
std::istringstream iss(line);
float v[5];
// The input operator `>>` returns the stream
// And streams can be used as a boolean value
// A stream is "true" as long as everything is okay
while (iss >> v[0] >> v[1] >> v[2] >> v[3] >> v[4])
{
for (int i = 0; i < 5; i++) {
array[numberOfLines][i] = v[i];
}
numberOfLines++;
}
// Flush the standard output stream and print a newline
std::cout << std::endl;
} else {
firstLine = false;
}
}
return numberOfLines ;
}
int main() {
string filename;
float array[][5];
cout << "enter the filemane" << endl;
getline(cin, filename);
int numberOfLines = fillArray(filename, array);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.