-2

Well I know using cin we can't read multiple strings . But the behaviour of getline here in this program is hard to understand . I am not able to figure out what is issue in it . Is it I can't use cin and getline in tandem ?

#include <iostream>
#include <string>

int main()
{
  std::string name;
  std::cout << "What is your name? ";
  std::cin>>name;
  std::cout << "Hello, " << name << "!"<<std::endl;
  getline (std::cin, name);
  std::cout << "Hello, " << name << "!\n";
}

Input :
Jai Simha Verma 
Jai Simha Verma

OUTPUT:
What is your name? Hello, Jai!
Hello,  Simha Verma !
user3798283
  • 457
  • 3
  • 9
  • What is weird? What exactly do you want? –  May 06 '16 at 06:30
  • @Issac has described the behavior very well. it's expected behavior, but if you were expecting your code to read next line by "getline" call then you can skip the current line using "cin.ignore(streamsize, delim)". http://www.cplusplus.com/reference/istream/istream/ignore/ – Rana May 06 '16 at 06:56

1 Answers1

2

The code std::cin>>name; is equivalent to operator>>(std::cin, name); this calls the function (declared in <string>):

template <class CharT, class Traits, class Allocator> 
std::basic_istream<CharT, Traits>& operator>>(
        std::basic_istream<CharT, Traits>& is,
        std::basic_string<CharT, Traits, Allocator>& str);

With the template arguments CharT = char and Traits = std::char_traits<CharT>>

As per the documentation at: operator<<,>>(std::basic_string) This will first trim whitespace, then read until the first whitespace character is found (though this is not extracted from the stream). As such it only reads ‘Jai’, even though ‘Jai Simha Verma\n’ is the (unread) contents of the stream.

At your call getline (std::cin, name); the stream will contain ‘ Simha Verma\nJai Simha Verma\n’, but getline(); stops reading at the first newline character (it will extract it, but not append it to name), so it sets name to ‘ Simha Verma’ (including the leading space).

After this, the (unread) contents of std::cin will be ‘Jai Simha Verma\n’.

I am not sure what behaviour you would like so I am unable to suggest how to achieve this, rather I have merely explained what is happening.

Isaac
  • 796
  • 4
  • 12