我的程序有两个输入文件,其中一个是命令列表。该文件的每一行都是一个新命令,所以我想将此文件解析为一个数组。我被告知要使用动态增长的向量,这将消除对函数来计算文件中的行数然后使用该数据创建数组的需要。
这是我现在的程序:
#include<iostream>
#include<string>
#include<fstream>
#include<vector>
using namespace std;
//Prototypes
int parseLines(ifstream& countfile);
vector<string> parseLines(ifstream& countfile)
//counts number of lines in file passed to function
{
string line;
vector<string> lines;
int numberOfLines;
//reads through each line until end of file putting each line in a sperate entry of the vector
while(getline(countfile, line))
{
lines.push_back(line);
}
return lines;
}
int main (int argc, char* argv[])
{
int i;
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]);
if(!inputfp.is_open())
{
cerr << "failed to open input file\n";
return 1;
}
vector<string> inputVector;
vector<string> apptsVector;
inputVector = parseLines(inputfp);
for(i=0; i<= inputVector.size(); i++)
{
cout << "Input " << i << ": " << inputVector[i] << endl;
}
return 0;
}
我在编译时遇到了这个很长的错误,我不太明白:
$ g++ calendar.cpp
calendar.cpp: In function ‘std::vector<std::basic_string<char> > parseLines(std::ifstream&)’:
calendar.cpp:17:46: error: new declaration ‘std::vector<std::basic_string<char> > parseLines(std::ifstream&)’
calendar.cpp:14:5: error: ambiguates old declaration ‘int parseLines(std::ifstream&)’
calendar.cpp: In function ‘int main(int, char**)’:
calendar.cpp:58:37: error: no match for ‘operator=’ in ‘inputVector = parseLines((* & inputfp))’
calendar.cpp:58:37: note: candidate is:
In file included from /usr/include/c++/4.7/vector:70:0,
from calendar.cpp:9:
/usr/include/c++/4.7/bits/vector.tcc:161:5: note: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = std::basic_string<char>; _Alloc = std::allocator<std::basic_string<char> >]
/usr/include/c++/4.7/bits/vector.tcc:161:5: note: no known conversion for argument 1 from ‘int’ to ‘const std::vector<std::basic_string<char> >&’
我觉得我不太明白如何使用向量。