c++,从文件写入地图
我只是在C ++上的新手,我尝试从文件中读取并将内容写入映射< string,float>。 但是只有文件的第一个元素才能映射,而我不能弄清楚原因。
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!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在告诉
getline()
读取直到遇到'\ 0'
(nul)字符,但您的文件中没有此类字符,因此整个文件获取在第一个调用上读取String
,然后仅从String
中提取第一组值,丢弃其余数据。To read the file line-by-line, you need to change the 3rd parameter of
getline()
to'\n'
instead:Or, just drop the 3rd parameter entirely因为
'\ n'
是默认分界符: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 thestring
on the 1st call, and then you extract only the 1st set of values from thestring
, 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:Or, just drop the 3rd parameter entirely since
'\n'
is the default delimiter: