检测文本文件中的空行

Detecting empty line from text file

本文关键字:文本 文件 检测      更新时间:2023-10-16

我有这样的文本文件:

7
a
bkjb
c

dea

hash_table是一个数组,使得每行line no.-2=index of hash_table array对应于数组中的一个元素。该元素可以是空行或字符,如"an"在文本文件中如下所示:

a
//empty line

第一个数字用于确定数组hash_table的大小。运算符<<没有将空行或""字符视为字符串,因此不会添加到数组中。我试过这个但没有用.这是我的尝试:

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::getline() 而不是 std::ifstream::operator >>()>>运算符将跳过空格,包括换行符。

std::string line;
while (std::getline(codes, line)) {
    //...do something with line
}