Greetings.
I'm trying to write a program that reads a txt file one line at a time and then extracting certain words and numbers from that line and storing them into strings and int (or floats), respectively.
So, an example line from the file would be:
field_1: string1 field_2: float1 field_3: int1 field_4: string2
then with the program store them in the following manner:
std::string p1 = string1
std::float f1= float1
std::int i1= int1
std::string p2 = string2
I think I know how to do it using a loop with getline(), string.find(), and str.substr().
Here is the program:
On the program the "field_n" are replaced by the corresponding variable.
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <fstream>
using namespace std;
string line, p1, p2;
int s1;
float f1;
ifstream myfile ("inputfile.txt");
int main()
{
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line <<endl;
s1 = int(line.find("field_1 ")) + 8;
s2 = int(line.find("field_2 ")) + 8;
s3 = int(line.find("field_3 ")) + 8;
s4 = int(line.find("field_4 ")) + 8;
p1 = str.substr (s1);
p2 = str.substr (s2);
p3 = str.substr (s3);
p4 = str.substr (s4);
}
}
else cout << "Unable to open file";
return 0;
}
And I know that I need to process the strings in order to convert them into ints or floats. I haven't included that part.
So I'm making this post to see if anybody knows a better way to do what I'm trying to do, I'd appreciate any help. I'm also making this post because I think that using this I can achieve what I'm trying to do but I read on the other 3 topics regarding substrings that using substring on a loop is very inefficient, so again I'd take any suggestions. Lastly, my program doesn't recognize the str.substr command. I get the following error:
'str' was not declared in this scope
Thanks for any help provided.