Hey guys,
I´ve read a lot of similar questions here in the last hours, but I still didn´t find out how to do it.
I want to read line by line from a txt file, which contains something like
Hannover Berlin 343.34
in every line.
I´ve ended up with something like this:
1 2 3 4 5 6 7 8 9 10 11 12
string s,z;
float g;
ifstream infile("bsp.txt");
while(infile >> s >> z >> g){
k.getQuelle()->setMarkierung(s);
k.getZiel()->setMarkierung(z);
k.setGewicht(g);
insert(k);
}
But it´s not reading anything from the file.
It would be great if anybody could give me a hint on what I have to change.
Thanks in advance!
When you have more values on a line, the best/easy way is to read the whole line in a string first, then extract from that string the information you need, based on the pattern you have. In this case before the first space you have a word, after that another word, and after the second space a number(witch you will extract as a substring and then convert to a float
In this topic there was an almost identical problem, unfortunatly the op deleted hi's posts ... but my answer still applies. http://www.cplusplus.com/forum/beginner/101481/
Well it does open the file.
@nedo thanks for your answer, but I still don´t understand how to do it. Your example uses linefirst and linelast. Do I have to add the size of the first selected string to get the second? Isn´t there an easier way.
Based on your example, i will assume that all the lines respect this rule:
word, space, word, space, number
if this case you something like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
while(!infile.eof())
{
double num; // the number
string firstWord; // first word
string secondWord; // second word
string last; // number before transformation to double;
string line; // the whole line
getline(infile, line)
int pos = line.find_first_of(" ", 0); // position of the first space
firstWord = line.substr(0, pos); // extract the first word
secondWord = line.substr((pos + 1), line.find_first_of(" ", (pos + 1))); // extract the second word
pos = line.find_first_of(" ", (pos + 1)); // position of the second space
last = line.substr((pos + 1), line.find_first_of(" ", (pos + 1))); // the number
num = atof(last.c_str(); // convert string number to double
}
There might be some errors due to the fact that the code is writen straight in the browser window. See if it works.
ifstream infile("bsp.txt");
string line;
while (getline(infile, line))
{
string s, z;
float g;
istringstream ss(line);
ss >> s >> z >> g;
k.getQuelle()->setMarkierung(s);
k.getZiel()->setMarkierung(z);
k.setGewicht(g);
insert(k);
// next line for debugging purposes, remove when it is working
cout << "s: " << s << " z: " << z << " g: " << g << endl;
}
Hey guys, thank you all for your help. Apparently the version I posted was working already. But without Nedos version I wouldn´t have figured out my mistake, so it helped me anyway. :)