簡體   English   中英

從文本文件中讀取字符串和浮點數

[英]Reading strings and floats from a text file

我意識到有類似的問題,但是,這些解決方案似乎只有在一組數據在同一行時才有效。

我有一些在文本文件中結構化的數據,如下所示:

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

每3行一個新生,一共6個學生。 我的代碼一直有效,直到它到達分配標記的部分,我需要將其作為float讀入,其他所有內容都是字符串。

我發現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;
}

我有要求逐行獲取數據,假設每三行是一個新學生。 我的下一個要求是第三行是浮點數,但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);

        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