Reputation: 344
I'm trying to read a file using c++ but I am only looking to store certain things. This is what my file looks like
stufff
stuff
more stuff
.
.
.
data_I_want 32 34 45
data_I_want 52 22 34
stuff again
.
.
.
end of file
So far I have written this code, but the output is always 0.
ifstream file;
file.open("stuff.txt");
string line;
double v;
if(file.is_open()){
while(getline(file,line) && line.compare("data_I_want")){
file>>v;
cout<<v<<endl;
}
file.close();
}
Upvotes: 0
Views: 39
Reputation: 3105
line is data_I_want 32 34 45, not just data_I_want. May be you want to find lines starting with data_I_want
And here is how you use get substring of a string (taken from here):
// string::substr
#include <iostream>
#include <string>
int main ()
{
std::string str="We think in generalities, but we live in details.";
// (quoting Alfred N. Whitehead)
std::string str2 = str.substr (12,12); // "generalities"
std::size_t pos = str.find("live"); // position of "live" in str
std::string str3 = str.substr (pos); // get from "live" to the end
std::cout << str2 << ' ' << str3 << '\n';
return 0;
}
Upvotes: 1