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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19123334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:32:03  来源:igfitidea点击:

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

c++arraysfile-iofstreamdynamic-arrays

提问by user1334858

I am trying to use std::getline()in my project to read in a text file into an array of strings.

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

Here is my code:

这是我的代码:

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]);
}

So after doing some decoding I know that the getline() is not placing any value in the array of strings. It seems to place a null string in the array.

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

The goal is to read in a text file like:

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

Hello
Bye
See you later

The array will be filled like:

该数组将被填充如下:

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

回答by P0W

Why so trouble ?

为什么这么麻烦?

Simply use std:vectorof std::string

只需使用std:vectorstd::string

std::string str;

std::vector <std::string> vec;

while ( std::getline(ifs,str) )
{
  vec.push_back(str) ;
}

If you really need an array of string

如果你真的需要一个数组 string

do :

做 :

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

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

And copy the elements from vecto in_file

并将元素从 复制vecin_file

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

回答by LihO

Never wrap reading from the stream with the following loop:

切勿使用以下循环从流中读取数据:

while ( !ifs.eof() )

At some websites, you will find an example telling you to do:

在某些网站上,您会找到一个示例,告诉您执行以下操作:

while ( ifs.good() )

which is a bit better than the first loop, yet still it is quite error prone and not advisable to do. Have a look at: Why is iostream::eof inside a loop condition considered wrong?

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

The most common ways of reading the files are either using std::getlinewhen reading by lines:

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

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

or simply using >>operator when reading by words or extracting concrete types (e.g. numbers):

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

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


And to your dynamically allocated C-style array of std::stringobjects: avoid dynamic allocation as much as possible. Believe me, you don't want to take care of memory management on your own. Prefer using objects with automatic storage duration. Take advantage of what the standard library provides.
As it was pointed out already: use STL containers such as std::vectorinstead of C-style arrays:

对于动态分配的 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);
}