如何使用 std::getline() 将文本文件读入 C++ 中的字符串数组
How to use std::getline() to read a text file into an array of strings in C++?
我正在尝试在我的项目中使用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];
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '