Read text file to build a vector.
Hi,
I am trying to read a text file "filename.txt" to build a vector of doubles. I used following code which works fine when I am using outside ROS. However, when I include this code as a part of my .cpp file in a ROS package, it does not work. At line while(myFile >> value)
, it does not read any thing and hence does not enter the loop. Any help is appreciated.
#include <fstream>
#include <vector>
#include <iostream>
std::vector<double> vec;
void readDATA(){
double value;
std::ifstream myFile;
myFile.open("filename.txt", std::ios::app);
if (myFile.is_open()){
std::cout << "File is open."<<std::endl;
while(myFile >> value){
vec.push_back(value);
std::cout << "value is " <<value<< std::endl;
}
myFile.close();
}
else std::cout << "Unable to open the file";
}
int main(){
readDATA();
return 0;
}
"filename.txt" is relative to you current directory. If the file is relative to an ROS package, you can use #include <ros package.h=""> and ros::package::getPath("some_package")
Thanks kmhallen, I replaced line number 10 with following code: myFile.open((ros::package::getPath("package_name")+"/filename.txt"), std::ios::app); and included the header file as #include <ros package.h="">. Still getting "no matching function" error. Any idea please?
PS: The error is: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::basic_string<char>, const openmode&)’