I have posted my attempt of writing the code, My problem with the function is st
ID: 3786075 • Letter: I
Question
I have posted my attempt of writing the code, My problem with the function is storing the data in the vectors. How can I get both vectors to store the information from the columns? Do I have the vectors declared correctly in the main function?
using namespace std; void read Data (const string & data vector double first double & 8e cond int temp int i 0: ifstream file (data.c str Eif (!file is open f //if the file does not open display an error message cout Error opening tunnel1.dat" endl. exit (1) E while (file temp f attempting to create a loop to get doubles on the left of file first push back. temp cout "File contains the values endl E for (int i i first size ++i) f cout first at (i) endl int main. string filename: double amount 100.0 putting in a big number vector double r On amount. vector double two (amount); cout Enter name of input data file endl; cin filename read Data (filename, one, two); return 0;Explanation / Answer
C++ working code:
#include <bits/stdc++.h>
using namespace std;
void readData( string filename , vector<float> angles, vector<float> coefficients)
{
string line;
ifstream myfile (filename.c_str());
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
float c1 = atof(tokens[0].c_str() ) ;
float c2 = atof(tokens[1].c_str() ) ;
angles.push_back(c1);
coefficients.push_back(c2);
cout << c1 << " " << c2 << endl;
}
myfile.close();
}
else
{
cout << "Unable to open file" << endl;
exit(1);
}
}
int main()
{
cout << "Please enter filename" << endl;
string filename;
cin >> filename;
std::vector<float> one;
std::vector<float> two;
readData(filename.c_str(), one,two);
return 0;
}
Sample output:
1)
Please enter filename
input1.dat
1.1 2.2
3.3 4.4
5.5 6.6
7.111 8.888
2)
Please enter filename
aa
Unable to open file