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

use*_*858 8 c++ arrays file-io fstream dynamic-arrays

我试图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]);
}
Run Code Online (Sandbox Code Playgroud)

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

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

Hello
Bye
See you later
Run Code Online (Sandbox Code Playgroud)

该数组将被填充如下:

in_file [0] = Hello
in_file [1] = Bye
in_file [2] = See you later
Run Code Online (Sandbox Code Playgroud)

P0W*_*P0W 10

为什么这么麻烦?

只需使用std:vectorstd::string

std::string str;

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

while ( std::getline(ifs,str) )
{
  vec.push_back(str) ;
}
Run Code Online (Sandbox Code Playgroud)

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

做:

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

并将元素复制vecin_file

for(size_t i=0;i<vec.size();i++)
 in_file[i] = vec[i];
Run Code Online (Sandbox Code Playgroud)


Lih*_*ihO 8

永远不要使用以下循环从流中读取:

while ( !ifs.eof() )
Run Code Online (Sandbox Code Playgroud)

在某些网站上,您会找到一个示例告诉您:

while ( ifs.good() )
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

std::string word;
while ( ifs >> word ) {               
    ...
}
Run Code Online (Sandbox Code Playgroud)

并动态分配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);
}
Run Code Online (Sandbox Code Playgroud)