如何使用 std::getline() 将文本文件读入 C++ 中的字符串数组

How to use std::getline() to read a text file into an array of strings in C++?

本文关键字:C++ 数组 字符串 文件 文本 std 何使用 getline      更新时间:2023-10-16

我正在尝试在我的项目中使用std::getline()将文本文件读取到字符串数组中。

这是我的代码:

ifstream ifs ( path );
string * in_file;
int count = 0;
while ( !ifs.eof() )
{
    ++count;
    if ( count == 1 )
    {
        in_file = new string[1];
    }
    else
    {
            // Dynamically allocate another space in the stack
    string *old_in_file = in_file;
    in_file = new string[count];
            // Copy over values
    for ( int i = 0 ; i < ( count - 1 ) ; i++ )
    {
        in_file[i] = old_in_file[i];
    }
    delete[] old_in_file;
    }
            // After doing some debugging I know this is the problem what am I 
            // doing wrong with it?
    getline(ifs,in_file[count - 1]);
}

因此,在进行一些解码后,我知道getline()没有在字符串数组中放置任何值。它似乎在数组中放置了一个空字符串。

目标是读取文本文件,例如:

Hello
Bye
See you later

数组将按如下方式填充:

in_file [0] = Hello
in_file [1] = Bye
in_file [2] = See you later

切勿使用以下循环包装流中的读取:

while ( !ifs.eof() )

在某些网站上,您会发现一个例子告诉您执行以下操作:

while ( ifs.good() )

这比第一个循环好一点,但它仍然很容易出错,不建议这样做。看看:为什么循环条件中的iostream::eof被认为是错误的?

读取

文件的最常见方法是在按行读取时使用std::getline

std::string line;
while ( std::getline(ifs, line) ) {
    if (line.empty())                  // be careful: an empty line might be read
        continue;                      
    ...
}

或者在按单词阅读或提取具体类型时简单地使用>>运算符(例如 数字):

std::string word;
while ( ifs >> word ) {               
    ...
}

对于动态分配的 C 样式std::string对象数组:尽可能避免动态分配。相信我,您不想自己处理内存管理。首选使用具有自动存储持续时间的对象。充分利用标准库提供的功能。
正如已经指出的那样:使用 STL 容器(如 std::vector 而不是 C 样式数组):

std::ifstream ifs(path);
std::vector<std::string> lines;
std::string line;
while ( std::getline(ifs, line) )
{
    // skip empty lines:
    if (line.empty())
        continue;
    lines.push_back(line);
}

为什么这么麻烦?

只需使用std:vector std::string

std::string str;
std::vector <std::string> vec;
while ( std::getline(ifs,str) )
{
  vec.push_back(str) ;
}

如果你真的需要一系列string

做:

string * in_file = new string[vec.size()];

并将元素从vec复制到in_file

for(size_t i=0;i<vec.size();i++)
 in_file[i] = vec[i];