0

As far as I have read cin "ignores" spaces tab and new lines while taking input but when I try to input my name in a character array then why does it only stores the first part of my name?

//I input John Ive

char a[100];
cin>>a;
cout<<a;
//I get John as output
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • skip leading space, and stop at first space... – Jarod42 Dec 12 '20 at 10:31
  • This question has nothing to do with `std::cin`. It's the **stream extractor** (`operator<<`) that treats whitespace as separators. Other forms of reading (such as `std::getline`) will happily copy whitespace from `std::cin` (and any other `istream`) into the target array. – Pete Becker Dec 12 '20 at 16:31

1 Answers1

1

Because the steam extractor (operator>>) stops reading at the space, you would have to call it twice. (Thanks @PeteBecker).

Alternatively if you want to read an entire line you should do something like this using getline():

#include<iostream>
#include<string>
using namespace std;

int main()
{
    cout << "Enter name:\n";

    string s;
    getline(cin,s);

    cout << "You entered " << s << '\n';
}
Luca Angioloni
  • 2,243
  • 2
  • 19
  • 28
  • `std::cin` does not stop reading at the space. It's the **steam extractor** (`operator>>`) that does that. – Pete Becker Dec 12 '20 at 16:33
  • @PeteBecker Yes you are right.... I just wrote in simple terms, and I oversimplified. Sorry, I will update the answer. Thank you for your comment. – Luca Angioloni Dec 12 '20 at 16:34
  • It's a common oversimplification which, unfortunately, can lead to massive confusion. `std::cin` is an object. It doesn't do anything on its own; it's functions that do things. – Pete Becker Dec 12 '20 at 16:36