im just new at c and I try to read from a file and write the content into a map<string, float>. But only the first element of my file gets mapped and i cant figuer out why.
The file looks like this:
E:16.93
N:10.53
I:8.02
...
And the code i got for this part so far:
std::map<char, float> frequenciesM;
fstream frequencieFile("frequencies.txt", std::ios::in);
if(!frequencieFile){
cout << "No such File!";
}else{
std::string line;
char ch;
std::string sub;
float fl;
while (std::getline(frequencieFile, line, '\0')) {
ch = line[0];
sub = line.substr(2);
fl = std::stof(sub);
frequenciesM[ch] = fl;
}
}
When i try to print out the size and content of my map, this is what i get:
Size: 1
E: 16.93
Thx for any help and suggestions!
CodePudding user response:
You are telling getline()
to read until a '\0'
(nul) character is encountered, but there is no such character in your file, so the entire file gets read into the string
on the 1st call, and then you extract only the 1st set of values from the string
, discarding the rest of the data.
To read the file line-by-line, you need to change the 3rd parameter of getline()
to '\n'
instead:
while (std::getline(frequencieFile, line, '\n'))
Or, just drop the 3rd parameter entirely since '\n'
is the default delimiter:
while (std::getline(frequencieFile, line))