c++ - 为什么我的计数线函数总是返回 0?

标签 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;
}

最佳答案

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

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将线添加到 vector 。这会更容易并且更有效率,因为您不必两次读取文件。您还能要求什么!

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

关于c++ - 为什么我的计数线函数总是返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16293919/

相关文章:

c++ - 这个c++程序没有执行什么?

c++ - 作为 friend 的模板参数

c++ - 软阴影 : Spherical Area Light Source

c++ - std::vector 内存分配问题

c++ - 初始化一个以 shared_ptr 作为值的 const 映射

c++ - 如何翻转像素数据的Y轴

c++ - 长整数的表示

c++ - 更改 Eclipse CDT 项目的输出目录

c++ - QTreeView 放置在 QDockWidget 中时不显示

c++ - OpenGL + SDL 有时会脱离坐标