trying to read from a file

Hey guys I am trying to read from a file and put that into a string called data,
which I believe I am doing correctly. When I print out whatever is in data in the first while loop, it prints it out correctly, but when I try to print out data outside of the while loop nothing gets printed. I am not able to figure this problem out please help. Thanks in advance (code below)

#include <fstream>
#include <string>
#include <iostream>

using namespace std;

int readFile(char* file){
ifstream readFile;
readFile.open(file);
size_t marker;
string data, number="";

if(readFile.is_open()){

while(readFile.good()){
getline(readFile, data);
cout << data <<"\n";
}
cout << "works";
cout << data;
}
else{
cout << "error opening file \n";
return 1;
}
cout << data;
cout << "1";
marker = data.find('.');
//cout << marker;
marker = marker +1;
number = data.substr(marker, 10);
cout << number << "\n";
return 0;
}

int main(){
readFile("ReadTest.txt");
return 0;
}
Each iteration of your while loop is overwriting data until eof which then data is empty.

Also I would not use .good()
Write your read loop this way

1
2
3
while( getline( readFile, data ) )
{
}
Thanks ill try that out
Topic archived. No new replies allowed.