-1

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

这是我现在的程序:

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

我觉得我不太明白如何使用向量。

4

3 回答 3

6

原型

int parseLines(ifstream& countfile);

实现

vector<string> parseLines(ifstream& countfile)

返回类型不同。

于 2013-04-30T07:31:22.043 回答
2

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

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

应该

   for (i = 0; i < inputVector.size(); i++)
于 2013-04-30T07:37:41.053 回答
0

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

首先更改:

vector<string> parseLines(ifstream& countfile); 

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

于 2013-04-30T07:34:26.917 回答