为什么我的countlines函数总是返回0?

时间:2013-04-30 06:50:41

标签: c++

所以我正在为一个简单的日历应用程序创建一个程序,该应用程序从一个文件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;
}

4 个答案:

答案 0 :(得分:6)

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

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

由于各种原因,文件无法打开,您应该始终检查这一点。

BTW不使用数组来保存输入行,请使用std::vector<std::string>。然后,您可以使用push_back将线条添加到矢量。这将更容易更高效,因为您不必两次读取文件。还有什么可以要求的!

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

答案 1 :(得分:2)

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

这意味着您的open电话会失败,但您不会检查。

答案 2 :(得分:2)

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

尝试:

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

答案 3 :(得分:0)

您正在尝试访问null的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;

}