簡體   English   中英

如何使用ifstream C ++讀取子字符串

[英]How to read substring with ifstream C++

這是我的文件txt的內容:

1        Joey        1992

2        Lisa        1996

3        Hary        1998

我有一個結構:

struct MyStruct
{
    int ID;
    char *Name;
    int Old;
};

我有一個main():

int main ()
{
    MyStruct *List;
    int Rows, Columns;
    ReadFile (List, Rows, Columns, "file.txt");
    return 0;
}

現在,我想編寫一個函數ReadFile來從文件txt獲取信息並存儲到List中,除了存儲行和Colums:

void ReadFile (MyStruct *&List, int &Rows, int &Colums, char const *path)
{
    // need help here
}

我知道如何使用ifstream從txt讀取整數,但我不知道如何讀取子字符串,例如:

“喬伊”,“麗莎”和“哈瑞”

將每個存儲到char *Name

請幫我。 非常感謝 !

您似乎在進行舊學校練習:使用數組和c-string存儲數據元素,以及手動內存管理的所有麻煩。

第一種(老派)方法

我將只使用非常基本的語言功能,並避免任何現代C ++功能

void ReadFile (MyStruct *&List, int &Rows, int &Colums, char const *path)
{
    const int maxst=30;        // max size of a string
    Rows=0;                    // starting row
    ifstream ifs(path); 
    int id; 
    while (ifs>>id) {
        MyStruct *n=new MyStruct[++Rows];  // Allocate array big enough 
        for (int i=0; i<Rows-1; i++)       // Copy from old array
            n[i] = List[i]; 
        if (Rows>1)
           delete[] List;                  // Delete old array
        List = n;
        List[Rows-1].ID = id;              // Fill new element
        List[Rows-1].Name = new char[maxst];                          
        ifs.width(maxst);                 // avoid buffer overflow
        ifs>>List[Rows-1].Name;           // read into string
        ifs>>List[Rows-1].Old;                     
        ifs.ignore(INT_MAX,'\n');         // skip everything else on the line
    }
}

這假定在調用函數時ListRows未初始化。 請注意,此處不使用Columns

請注意,當您不再需要List時,您必須清除混亂:首先要刪除所有Name ,然后刪除List

如何在更現代的C ++中實現它

如今,你不再使用char*而是string

struct MyStruct {
    int ID;
    string Name;
    int Old;
};

你不會使用數組來保存所有項目,而是使用像vector這樣的容器:

int main ()
{
    vector<MyStruct> List;
    ReadFile (List, "file.txt"); // no nead for Rows. It is replaced by List.size()
    return 0;
}

然后你會這樣讀:

void ReadFile (vector<MyStruct>& List, string path)
{
    ifstream ifs(path); 
    MyStruct i;  

    while (ifs>>i.ID>>i.Name>>i.Old) {
        List.push_back(i);  // add a new item on list                     
        ifs.ignore(INT_MAX,'\n');         // skip everything else on the line
    }
}

不用擔心內存管理; 不用擔心字符串的最大大小。

暫無
暫無

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

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