我的代码打开一个文本文件,计算行数,分配一个数组来存储所有行,然后调用一个函数用每行填充这个数组。此函数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);
CountLines功能:
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的'\ n'问题有关但是当我将get指针设置为0并且文件以普通文本而不是行开头时,我无法理解为什么它用空字符串填充templine。
答案 0 :(得分:5)
您不需要先计算行然后读取行。你可以做到
#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,没有任何大惊小怪或手动内存管理。
答案 1 :(得分:1)
您的代码中存在太多错误。
istream::getline()
的参数错误CountLines()
指针不是玩具,你最好选择Tino Didriksen的解决方案。
如果你真的喜欢char和指针,它应该是这样的:
#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;
}
答案 2 :(得分:-1)
您的错误在于此代码:
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;
}
}