c++,从文件写入地图

发布于 2025-01-21 22:55:57 字数 876 浏览 0 评论 0原文

我只是在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最偏执的依靠 2025-01-28 22:55:57

您正在告诉getline()读取直到遇到'\ 0'(nul)字符,但您的文件中没有此类字符,因此整个文件获取在第一个调用上读取String,然后仅从String中提取第一组值,丢弃其余数据。

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因为'\ n'是默认分界符:

while (std::getline(frequencieFile, line))

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文