为什么countlines函数总是返回0

Why does my countlines function always return 0?

本文关键字:返回 countlines 函数 为什么      更新时间:2023-10-16

所以我正在制作一个简单的日历应用程序,该程序从文件input.csv(它是一个文本文件,有两列,使用逗号和新行分隔每个命令)中读取输入。

我要做的第一件事是计算输入文件的行数,这是作为命令行中的第三个参数传递的,所以我可以创建一个数组来单独保存每行,但函数countLines总是返回0!

项目代码:

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

//Prototypes
int countLines (ifstream& countfiles);

int countLines(ifstream& countfile)
//counts number of lines in file passed to function
{
   string line;
   int numberOfLines;
   numberOfLines = 0;
   //reads through each line until end of file
   while(getline(countfile, line))
   {
       numberOfLines++;
   }
   return numberOfLines;
}

int main (int argc, char* argv[])
{
    if(argc != 3) cout << "Usage: calendar.out datafile inputfile";
    //Create input streams to both files
    ifstream apptsfp;
    ifstream inputfp;
    //Open streams to both files
    apptsfp.open(argv[2]);
    inputfp.open(argv[3]);
        int numberOfInputs=0;
    numberOfInputs = countLines(inputfp)-1;
        cout << "number of input commands: " << numberOfInputs << endl;
    return 0;
}

几乎可以肯定,因为您没有打开输入文件。

inputfp.open(argv[3]);
if (!inputfp.is_open())
{
    cerr << "failed to open input file " << argv[3] << 'n';
    return 1;
}

文件可能由于各种原因无法打开,您应该经常检查这一点。

顺便说一句,不要使用数组来保存输入行,使用std::vector<std::string>。然后你可以用push_back把直线加到向量上。这将更容易更有效,因为您不需要读取文件两次。你还能要求什么呢!

std::vector<std::string> lines;
std::string line;
while (getline(inputfp, line))
    lines.push_back(line);

似乎您只需要两个参数,而不是您在问题中所说的三个("第一个"参数是程序名称)。这意味着输入文件是在argc[2]中,而argv[3]是一个NULL指针。

这意味着您的open调用将失败,但您不检查。

您对argv[3]的访问不正确。第二个文件名(第三个参数,包括arg[0]中的程序名)位于slot 2(数组从零开始)。

试题:

apptsfp.open(argv[1]);
inputfp.open(argv[2])

您正在尝试访问为空的argv[3]。试试这个:-

int main (int argc, char* argv[])
{
    if(argc != 3)
        cout << "Usage: calendar.out datafile inputfile";
    //Create input streams to both files
    ifstream apptsfp;
    ifstream inputfp;
    //Open streams to both files
    apptsfp.open(argv[1]);
    inputfp.open(argv[2]);
    int numberOfInputs=0;
    numberOfInputs = countLines(inputfp)-1;
    cout << "number of input commands: " << numberOfInputs << endl;
    return 0;
}