如何使用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 中获取信息并存储到一个列表中,旁边存储行和列:

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

我知道如何使用ifstream从txt中读取整数,但不知道如何读取子串,如:

"Joey", "Lisa" and "Hary"

将每个存储到 char *Name.

请帮助我。非常感谢!

您似乎在做旧式练习:您使用数组和 c 字符串来存储数据元素,需要手动进行内存管理。

第一种(老派)方法

我将只使用非常基本的语言特性,避免使用任何现代 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
    }
}

不用担心内存管理;不用担心字符串的最大大小。