我不太明白为什么我得到关于矢量的这个错误

时间:2013-04-30 07:29:20

标签: c++

我的程序有两个输入文件,其中一个是命令列表。该文件的每一行都是一个新命令,所以我想将这个文件解析成一个数组。我被告知在动态增长时使用向量,这样就不需要函数来计算文件中的行数,然后使用该数据来创建数组。

以下是我的计划:

#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> >&’

我觉得我不太明白如何使用载体。

3 个答案:

答案 0 :(得分:6)

原型

int parseLines(ifstream& countfile);

实现

vector<string> parseLines(ifstream& countfile)

退货类型不同。

答案 1 :(得分:2)

不是问题,但另一个错误是

   for (i = 0; i <= inputVector.size(); i++)

应该是

   for (i = 0; i < inputVector.size(); i++)

答案 2 :(得分:0)

问题出在int parseLines(ifstream& countfile);函数声明中。与后来的vector<string> parseLines(ifstream& countfile)定义存在冲突:

先改为:

vector<string> parseLines(ifstream& countfile); 

此外,由于此函数定义在使用之前,您可以删除其声明。