Here we go again... I wrote a short program that tries to identify how many words are in a input stream. These are the source files and the header file:
4_exercise_5_read_function.cpp (the function that tries to create a vector from a input line)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include "4_exercise_5_read_function.h"
using std::istream; using std::vector;
using std::string;
istream& read(istream& is, vector<string>& v)
{
if (is)
{
v.clear();
string x;
while (is >> x)
v.push_back(x);
// clear the error state of the stream so that input will work next time
is.clear();
}
return is;
}
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "4_exercise_5_read_function.h"
using std::cin; using std::sort;
using std::cout; using std::streamsize;
using std::endl; using std::string;
using std::vector; using std::istream;
int main()
{
string cis;
vector <string> vec;
typedef vector <string>::size_type vec_sz;
read(cis, vec);
vec_sz size = vec.size();
cout << "The number of words of the given line is: " <<size<<endl;
return 0;
}
And the errors are:
1 2 3
4_exercise_5.cpp In function 'int main()':|
4_exercise_5.cpp on line 18: error: invalid initialization of reference of type 'std::istream&' from expression of type 'std::string'|
4_exercise_5_read_function.h on line 6: error: in passing argument 1 of 'std::istream& read(std::istream&, std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&)'|
I don't know what could cause those error. And I really searched a solution. The parameters of read function are lvalues, they have the same types. Maybe I can't read a vector of strings like that? Can you give me a soulution?
cis (=console input stream) represents the place where I want to store the line that i want to read from the console. After that (using cis as an argument for the read function) I want to store the words from cis into a vector (v). That's the purpose of read function: introduces each word from the input stream (example):
If you have your input in string cis, then you need to turn that into an input stream. The std::istringstream is designed for exactly that purpose:
1 2 3 4 5 6
std::string cis;
std::istringstream iss(cis); // make an input stream from your string
// ...
read(iss, vec); // now call read with the input stream containing your string