1

I want to read an std::string named destination from std::cin until a given delimiter. By default, std::istream::operator<< interrupts after a space when I do destination << std::cin. If destination were a char[], I could use std::getline.

What do we use for std::string?

YSC
  • 38,212
  • 9
  • 96
  • 149
Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76

2 Answers2

6

Your premise is wrong: std::getline does work with std::string:

template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input,
                                           std::basic_string<CharT,Traits,Allocator>& str,
                                           CharT delim );

This means you can read from std::cin to an std::string until a given delimiter:

std::string destination;
std::getline(std::cin, destination, '|');

('|' taken as an exemple delimiter)


Note: you should check getline's return before reading from destination. getline returns a reference to std::cin which can be converted to a bool whose value is true if the stream is in a correct state:

if (std::getline(std::cin, destination, '|') == false) {
    // error handling
}
Tas
  • 7,023
  • 3
  • 36
  • 51
YSC
  • 38,212
  • 9
  • 96
  • 149
0

Use std::getline, like this:

std::string InputWithSpaces;
std::getline (std::cin,InputWithSpaces);
std::cout << InputWithSpaces << std::endl; //test 1 2 3
Alexey Usachov
  • 1,364
  • 2
  • 8
  • 15