I have a program that imports data from a file input.txt. The file is very long and not all the data is needed.
I what to write a function getData() that inputs a string from the file, evaluates whether the string is numeric and returns it if it is, or moves onto the next string if not:
main(){
//Some double variables are defined
ifstream in;
in.open("input.txt"); // It is important that this is in the main program and not in the function
floatVariable0= getData(in);
floatVariable1= getData(in);
floatVariable2= getData(in);
//...
in.close()
//...
}
float getData(ifstream &in){
string str;
float rtnVal;
int isNum= 0;
int isDot= 0;
in >> str;
for( i=0; i<strlen(str)-1; i++) {
for(int j=0; j<=9; j++) {
if(atoi(&str[i]) != j || &str[i] != ".") {
isNum++;
}
if(&str[i] == "."){
isDot++
}
}
}
if(isDot<2 && isNum==0){
rtnVal = atof(str);
return rtnVal;
}else{
getData(in);
}
}
Not 100% sure the code within the getData() function works but for now just treat it as an example of what I want to do, My main concern is how to pass the in ifstream into the function. I've used an & but I know that doesn't work.
Any suggestions?
J Smith: In testing I've written a more simple version of the above function that simply prints to screen the string it inputs from the file and all it returns is a white space. I've got to go now but I'll post that tonight, maybe I've made a mess with the type of variables I used, or I should be using char[] rather than arrays. Seeing as you think I'm on the right track I'll check to make sure I'ts not something silly, thanks.
I do apologies it turns out that it is possible to pass an ifstream into a function by using by non-const reference (ie &). The reason my test code did not work was that I carelessly put the print statement before the line that read from the input file. I was so convinced that my approach to solving this problem was wrong that I failed to thoroughly check my test code before posting this question.
Sorry Bazzy and Jsmith, I hope this topic will turn out to be useful to someone in the future.