为什么countlines函数总是返回0
Why does my countlines function always return 0?
所以我正在制作一个简单的日历应用程序,该程序从文件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;
}
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 为什么countlines函数总是返回0