我正在尝试在我的项目中使用 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() )
这比第一个循环好一点,但仍然很容易出错,不建议这样做。看看:Why is iostream::eof inside a loop condition considered wrong?
最常见的读取文件的方法是在按行读取时使用 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 ) {
...
}
对于动态分配的 std::string
对象的 C 风格数组:尽可能避免动态分配。相信我,您不想自己处理内存管理。更喜欢使用具有自动存储持续时间的对象。充分利用标准库提供的功能。
正如已经指出的:使用 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);
}
关于c++ - 如何使用 std::getline() 将文本文件读入 C++ 中的字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19123334/