我的程序需要兩個輸入文件,其中之一是一個命令列表。文件的每一行都是一個新的命令,所以我想把這個文件解析成一個數組。我被告知要在動態增長時使用一個矢量,這樣就不需要函數來計算文件中的行數,然後使用該數據來創建數組。我不明白爲什麼我得到這個有關向量的錯誤
這是我的計劃是什麼現在:
#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> >&’
我覺得我不不太瞭解如何使用矢量。
你不能重載基於返回類型。 – 2013-04-30 07:30:57