簡體   English   中英

向量,結構和While循環-從文件讀取

[英]Vector, Structure and While loop - reading from a file

我有一個包含信息的文本文件。 看起來像這樣:

Rimas 252 45
Robertas 187 13
Jurgis 205 36
Matas 58 50
Antanas 145 5
10 20

如您所見,每一行都有三個不同的成員(名稱,第一個數字,第二個數字),直到最后一行只有兩個成員(兩個數字)。 我正在嘗試將此信息讀取到我的代碼中。 直到最后一行,一切都正常,因為它有兩個成員並且該行中沒有字符串。 我需要使我的代碼能夠識別不同的行並以其他方法讀取它,而不是與上面的行相同。


#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

struct lankytojai { // name, first number, second number
    string vardas;
    int litai;
    int ltcentai;
};

void read(vector<lankytojai> l) {
    ifstream failas("vvv.txt"); //reads three members correct, last two incorrectly
    int i = 0;
    while(failas) {

        lankytojai lan;
        int lt;
        string var;

        while(!(failas >> lan.ltcentai)) {
            failas.clear();
            if(failas >> var) {
                lan.vardas += var;
            }
            if(failas >> lt) {
                lan.litai = lt;
            }
            else {
                return;
            }
        }

        l.push_back(lan);
        cout << l[i].vardas << " " << l[i].litai << " " << l[i].ltcentai << endl;
        i++;
    }

}

int main() {
    vector<lankytojai> l;
    read(l);
    return 0;
}

只需將代碼重組為使用std::getline()獲取整行(作為std::string ),然后檢查其包含多少空格。

for (string line; getline(failas, line); ) {
    size_t space_count = count(line.begin(), line.end(), ' ');
    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM