简体   繁体   English

从文本文件中读取字符串和浮点数

[英]Reading strings and floats from a text file

I realize there are similar questions to this however, those solutions seem to only work if a group of data is on the same line.我意识到有类似的问题,但是,这些解决方案似乎只有在一组数据在同一行时才有效。

I have some data structured in text file like so:我有一些在文本文件中结构化的数据,如下所示:

<string student name>
<string course>
<float mark>
...

Every 3 lines is a new student, with a total of 6 students.每3行一个新生,一共6个学生。 My code works until it gets to the part where it assigns a mark, which I need to read in as a float , everything else is a string.我的代码一直有效,直到它到达分配标记的部分,我需要将其作为float读入,其他所有内容都是字符串。

I;ve found that getline() won't do this for me, wondering what is the best way to work with mixed types from a text file?我发现getline()不会为我这样做,想知道处理文本文件中的混合类型的最佳方法是什么?

#include <iomanip>
#include <ios>
#include <iostream>
#include <iterator>
#include <list>
#include <fstream>

struct Student {
    std::string name;
    std::string course;
    std::string grade;
    float mark;
};

int main() {

    Student students [6];
    std::string filename = "data.txt";
    std::ifstream file(filename);

    int i = 0;
    
    while(getline(file, students[i].name))
    {
        getline(file, students[i].course);
        getline(file, students[i].mark);
        
        if (students[i].mark > 89.5) {
            students[i].grade = "HD";
        } else {
            students[i].grade = "PASS";
        }
        
        ++i;
    }
    
    return 0;
}

I had the requirement to get the data line by line, assuming every three lines was a new student.我有要求逐行获取数据,假设每三行是一个新学生。 My next requirement was that the third line would be a float but getline() reads in as a string.我的下一个要求是第三行是浮点数,但getline()作为字符串读入。

My solution was to just create a temporary variable to take the string and then convert it to a float on the fly.我的解决方案是创建一个临时变量来获取字符串,然后即时将其转换为浮点数。

#include <iomanip>
#include <ios>
#include <iostream>
#include <iterator>
#include <list>
#include <fstream>

struct Student {
    std::string name;
    std::string course;
    std::string grade;
    float mark;
};

int main() {

    Student students [6];
    std::string filename = "data.txt";
    std::ifstream file(filename);

    int i = 0;
    
    while(getline(file, students[i].name))
    {
        getline(file, students[i].course);

        string mark; // <-- to hold the string
        getline(file, mark);
        students[i].mark = std::stof(mark);
        
        if (students[i].mark > 89.5) {
            students[i].grade = "HD";
        } else {
            students[i].grade = "PASS";
        }
        
        ++i;
    }
    
    return 0;
}
``

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM