Adapted from an earlier answer to a similar question (here):
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
namespace detail
{
class Line : public std::string
{
friend std::istream & operator>>(std::istream & is, Line & line)
{
return std::getline(is, line);
}
};
}
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
typedef std::istream_iterator<detail::Line> InIt;
std::copy_n(InIt(is), 1, dest);
}
int main()
{
std::vector<std::string> v;
read_lines(std::cin, std::back_inserter(v));
return 0;
}
This code should take only one line and saves it into the vector v. This is thanks to the use of std::copy_n function which takes the number of elements-to-be-copied as input. There is a quirk, though, reported here. Depending on your platform, one or two lines will be read even though only the first one will be saved into v.
That being said, if you want to make it fail-safe, you can just implement your own copy_n(...) function, like so:
template<class InIt, class Range, class OutIt>
OutIt own_copy_n(InIt first, Range count, OutIt dest)
{
*dest = *first;
while (0 < --count)
*++dest = *++first;
return (++dest);
}
Then instead of using std::copy_n(...) in you code, you can use own_copy_n(...).
This way you'll be sure you'll have to input one line only, and that that line will be saved into your vector v.