IF流获取线问题

ifstream getline issue

本文关键字:问题 获取 IF      更新时间:2023-10-16

我的代码打开一个文本文件,计算行数,分配一个数组来存储所有行,然后调用一个函数来用每一行填充这个数组。此函数 file.getline 调用返回空字符串:

代码如下:

typedef char* line;

char* filename=new char[256];
cout << "Type a file name: " << endl;
cin.ignore();
cin.getline(filename,255);
ifstream iFile(filename);
int nLines=CountLines(iFile);
line* LineArray = new line[nLines];
ReadLines(LineArray,iFile);

计数线功能:

int CountLines(ifstream &file)
{
line templine=new char[64];
int nLines=0;
while (!file.eof())
{
    file.getline(templine,64);
    if (*templine != 'n')
        nLines++;
}
delete [] templine;
return nLines;
}

这工作正常。但是,ReadLines 不会:

void ReadLines(line* LineArray, ifstream &file)
{
    line templine=new char[64];
file.seekg(0,ios::beg);
int i = 0;
while (!file.eof())
{
    if (*templine != 'n')
    {
        LineArray[i]=templine;
        i++;
    }
}
delete [] templine;
}

我有一种感觉,它与 getline 的""问题有关,但是当我将 get 指针设置为 0 并且文件以普通文本而不是一行开头时,我不明白为什么它用空字符串填充临时线。

您不需要先计算行数然后读取行数。你可以做

#include <istream>
#include <vector>
#include <string>
std::vector<std::string> ReadLines(std::istream& is) {
    std::vector<std::string> lines;
    std::string line;
    while (std::getline(is, line)) {
        lines.push_back(line);
    }
    return lines;
}

这将返回一个包含所有行的 std::vector,无需任何大惊小怪或手动内存管理。

你的代码中有太多的错误。

  • istream::getline()的参数错误
  • 您需要在CountLines()后清除 eof 标志
  • 错误的内存释放操作。
  • 等等
  • 等等...

指针不是玩具,你最好使用Tino Didriksen的解决方案。

如果你真的喜欢字符和指针,它应该看起来像这样:

#include <iostream>
#include <fstream>
#include <cassert>
using namespace std;
int CountLines(ifstream &fin) {
  char templine[1024];      // no need for dynamic allocation.
  int count = 0;
  while (fin.getline(templine, 1024))
    count++;
  return count;
}
void ReadLines(char** lines, int count, ifstream &fin) {
  fin.seekg(0, ios::beg);
  for (int i = 0; i < count; i++) {
    lines[i] = new char[1024];      // you need dynamic allocation here.
    fin.getline(lines[i], 1024);
    assert(fin.gcount() < 1024);    // assure the line is shorter than 1023 chars
  }
}
int main() {
  char filename[256];         // no need for dynamic allocation.
  cin.getline(filename, 256); // second parameter should be the same size of your buffer.
  ifstream fin(filename);
  int count = CountLines(fin);
  char** lines = new char*[count];
  // After CountLines() called, fin.eof is set, you need to clear it.
  // Otherwise fin.getline() won't do a thing.
  fin.clear();
  ReadLines(lines, count, fin);
  // When every thing is done, you need to free all the memory.
  for (int i = 0; i < count; i++)
    delete[] lines[i];
  delete[] lines;
}

你的错误在于这段代码:

if (*templine != 'n')

因为您正在检查行中的第一个符号。

您应该像这样更改代码:

int CountLines(ifstream &file)
{
    string line;
    int nLines=0;
    while(getline(file,line))
        nLines++;
    return nLines;
}

void ReadLines(string LineArray, ifstream &file)
{
    file.seekg(0,ios::beg);
    string line;
    while(getline(file,line))
    {
        LineArray += line;
    }
}