从文本文件中检测空行

时间:2013-10-28 16:38:34

标签: c++ file-io newline

我有这样的文本文件:

7
a

bkjb
c


dea

hash_table是一个数组,每行的line no.-2=index of hash_table array对应于数组中的元素。该元素可能是空行或像"a\n"这样的字符,在文本文件中会这样:

a
//empty line

第一个数字用于决定数组hash_table的大小。 <<< operator不将空行或'\ n'char作为字符串处理,因此不会添加到数组中。 我试过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);



}

注意:可能没有。随机序列的空行。

1 个答案:

答案 0 :(得分:2)

使用std::getline()代替std::ifstream::operator >>()>>运算符将跳过空格,包括换行符。

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