【发布时间】:2013-10-28 16:38:33
【问题描述】:
我有这样的文本文件:
7
a
bkjb
c
dea
hash_table 是一个数组,这样line no.-2=index of hash_table array 即每一行都对应于数组中的一个元素。该元素可能是空行或字符,如"a\n",在文本文件中会像这样:
a
//empty line
第一个数字用于决定数组hash_table 的大小。
this 但没用。 Here 是我的尝试:
ifstream codes ("d:\\test3.txt"); //my text file
void create_table(int size, string hash_table[]) //creating array
{ string a;
for(int i=0;i<size;i=i+1)
{
codes>>a;
char c=codes.get();
if(codes.peek()=='\n')
{char b=codes.peek();
a=a+string(1,b);
}
hash_table[i]=a;
a.clear();
}
}
void print(int size, string hash_table[])
{
for(int i=0;i<size;i=i+1)
{if(!hash_table[i].empty())
{cout<<"hash_table["<<i<<"]="<<hash_table[i]<<endl;}
}
}
int main()
{
int size;
codes>>size;
string hash_table[size];
create_table(size, hash_table);
print(size, hash_table);
}
注意:可以没有。具有随机序列的空行。
【问题讨论】:
-
没有。行中的字符数不固定
-
注意我链接到
std::string版本,不是std::istream::getline(应该很少使用到永远不会使用)。 -
所以您的代码将类似于
for (; std::getline(file, line); ++lineCount) { if(!line.empty()) table[lineCount]=line; }。 -
你不是很清楚。检测什么?你想存储每一行(不管它是否为空白),并按行号索引存储它们吗?所以使用
vector。