我试图在我的项目中使用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 ) {
...
}
以及动态分配的st样式的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);
}