【问题标题】:How to read substring with ifstream C++如何使用 ifstream C++ 读取子字符串
【发布时间】:2016-05-07 15:20:58
【问题描述】:

这是我的文件txt的内容:

1 乔伊 1992 2 丽莎 1996 3 哈里 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中读取整数,但不知道如何读取子字符串,如:

“乔伊”、“丽莎”和“哈利”

将每个存储到char *Name

请帮助我。非常感谢!

【问题讨论】:

  • C++ 上找到一本好书,并阅读解释astd::string 拥有的所有方法以及<algorithm> 提供的所有算法的章节。这就是您需要知道的全部内容。
  • 将字符串存储为std::string,除非您喜欢调试分段错误。它还使您想做的一切变得更容易。

标签: c++ ifstream readfile


【解决方案1】:

您似乎在做老派的练习:您使用数组和 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
    }
}

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

【讨论】:

  • 您的答案很容易理解,而且很有帮助。非常感谢! :)
猜你喜欢
  • 1970-01-01
  • 2019-06-03
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 2011-01-19
相关资源
最近更新 更多