【发布时间】:2013-10-01 18:29:45
【问题描述】:
我试图在我的项目中使用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
【问题讨论】:
-
如果你的任务允许你使用
std::vector,你应该这样做而不是new'ing 和delete'ing 每次迭代。 -
在 StackOverflow 中搜索“解析 getline 读取文件”。这个问题被问了太多次了。
标签: c++ arrays file-io fstream dynamic-arrays