I have a text file with 4 rows and 3 columns
(0.165334,0) (0.166524,-0.0136064) (-0.144899,0.0207161)
(0.205171,0) (0.205084,-0.0139042) (-0.205263,0.0262445)
(0.216684,0) (0.215388,-0.0131107) (-0.193696,0.0251303)
(0.220137,0) (0.218849,-0.0135667) (-0.194153,0.025175)
I wrote following code to print the values of FFTfile
. The script does not throw any errorm but it does not print the values. Any idea whats wrong?
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <dirent.h>
#include <string>
#include <sstream>
using namespace std;
class Point
{
public:
double x;
double y;
friend istream& operator>>(istream& input, Point& p);
friend ostream& operator<<(istream& s, Point& p);
double getX(void);
double getY(void);
};
double Point::getX(void){
return x;
}
double Point::getY(void){
return y;
}
istream& operator>>(istream& input, Point& p)
{
char c;
input >> c; // Read open parenthesis
input >> p.x;
input >> c; // Read comma
input >> p.y;
input >> c; // Read closing parenthesis
return input;
};
ostream& operator<<( ostream& s, Point& p)
{
s << p.getX() << ", " << p.getY();
return s;
}
vector<vector<Point> > LoadFFT(string path){
string Filename;
vector<vector<Point> > matrix;
Filename.append(path);
Filename.append("....txt");
ifstream fileFFT(Filename.c_str());
string raw_text;
while(getline(fileFFT, raw_text)){
vector<Point> row;
istringstream(raw_text);
Point p;
while( raw_text >> p ){
row.push_back(p);
}
matrix.push_back(row);
}
return(matrix);
}
int main(){
vector<vector<Point> > FFTfile=LoadFFT("...");
for (int i = 0; i < FFTfile.size(); i++)
{
for (int j = 0; j < FFTfile[i].size(); j++){
cout << FFTfile[i][j];
}
}
return(0);
}
If the file opened successfully, one issue seems to be the following set of lines:
istringstream(raw_text);
Point p;
while( raw_text >> p )
You have not created a std::istringstream
object at the point where you are issuing the >>
call. Instead a temporary object was created and immediately destroyed.
This should be:
istringstream strm(raw_text);
Point p;
while( strm >> p )
Having said this, I'm surprised the code compiled with no errors.