【问题标题】:Detecting empty line from text file从文本文件中检测空行
【发布时间】: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

标签: c++ file-io newline


【解决方案1】:

使用std::getline() 而不是std::ifstream::operator &gt;&gt;()&gt;&gt; 运算符将跳过空格,包括换行符。

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

【讨论】:

  • 这个while循环什么时候结束。它不应该将 EOF 添加到数组中。
  • @Nikhil 不会的。这是从文件中读取每一行的正确方法。如果您曾经检查过eof() 函数,那么您几乎肯定做错了。当它试图读取最后一行时,此条件将停止。
  • @BoBTFish 我确实喜欢这个click here,但仍然无法正常工作。编译器停止工作而不给出任何错误。查看 create_table() 函数
  • 当我删除 hash_table[i]=a; 时工作正常,当我用 cout a; 替换它时工作正常
  • @Nikhil:您的代码示例创建了一个 C 风格的字符串数组并将其称为哈希表。错误的原因在于,您将其设置为 C 样式的数组,其大小在编译时未知。使用 std::vector<:string> 并使用 .push_back 将新项目添加到向量中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
相关资源
最近更新 更多