C++'da Txt'den satır satır okuma işlemi

ErayPOLAT

Centipat
Katılım
16 Haziran 2022
Mesajlar
43
Daha fazla  
Cinsiyet
Erkek
Arkadaşlar bir projem projede txt de olan sayıları alıp işlem yapacağım.
Txt örnek olarak:
1.satır -> 12 25 45.
2.satır -> 12 25 45 65 75.
Bunların herbirini bir listeye atacağım hazır şablon kullanmayacağım dosyadaki tüm satırları okutmayı biliyorum fakat bana lazım olan şey ise 1. satırın sonuna geldiğinde 1listeden 2. listeye geçmem gerekecek bunu nasıl yapabilirim?
 
Aşağıya örnek bir yöntem bıraktım. Yaptığım iş, satır satır okutup bir vector'e kaydetmek. Ardından vector'den istediğim kadar satırı yazdırıyorum. İstersen vectorü array gibi kullanıp belirli bir satıra da ulaşabilirsin. Ama dikkat et eğer olmayan bir satıra ulaşmaya çalışırsan segmentation fault olur. Buna önlem olarak da LineCount < stvec.size() kullanabilirsin. Sorun olursa sorarsın.

C++:
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
using std::string;
class File {
    private:
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    string str;
    vector<string> stvec;
    bool ReadLine();
    public:
    File(FILE * fptr) {
        fp = fptr;
    }
    void printLines(size_t LineCount);
};
bool File::ReadLine() {
    if(fp == NULL ){
        return false;
    }
    while((read = getline(&line, &len, fp)) != -1) {
        str = line;
        stvec.push_back(str);
    }
    fclose(fp);
    if(line) {
        free(line);
    }
    return true;
}
void File::printLines(size_t  LineCount) {
    if(ReadLine()){
        if(LineCount <= 0) {
            exit(EXIT_FAILURE);
        }
        if(stvec.end() <= stvec.begin() + LineCount) {
            for(vector<string>::iterator i = stvec.begin(); i < stvec.end(); i++) {
                cout << * i << std::endl;
            }
        }
        if(stvec.end() > stvec.begin() + LineCount && LineCount > 0) {
            for(vector<string>::iterator i = stvec.begin(); i < (stvec.begin() + LineCount); i++) {
                cout << * i << std::endl;
            }
        }
    }
}
int main(int argc, char *argv[]) {
    FILE * fp = fopen("text.txt", "r");
    File F(fp);
    F.printLines(1);
    return 0;
}
 
Son düzenleme:

Yeni konular

Geri
Yukarı