0

I have declared a string array of [15]. Actually to store names. I execute it fine, but when I enter the complete name (including space; First name+[space]+last name) the program misbehaves. I cannot find the fault

I have declared multiple string arrays in the program, when I input the name with space it doesn't executes fine. I am using cin>> function to input in the array. like

string name[15];
int count=0;    cout << "enter your name" << endl;    
cin >> name[count];
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 2
    Related: https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces – Ch3steR Mar 23 '22 at 06:41
  • The program behaves exactly as it's supposed to, only your epxectations are wrong. See https://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt The third bullet point for function (2) states that it stops at the first whitespace. – Lukas-T Mar 23 '22 at 06:57
  • Also, before changing only *some* of the input to using getline, please consult [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – BoP Mar 23 '22 at 07:54

1 Answers1

2

I am using cin>> function to input in the array.

That is the problem. operator>> is meant for reading formatted input, so it stops reading when it encounters whitespace between tokens. But you want unformatted input instead. To read a string with spaces in it, use std::getline() instead:

string name[15];
int count=0;
cout << "enter your name" << endl;    
getline(cin, name[count]);

Online Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • i try doing it.. still the problem – MINAAM AHMAD Mar 23 '22 at 08:15
  • @MINAAMAHMAD [Works fine for me](https://ideone.com/tLoobx). Your problem must be in other code we can't see here. Please edit your question to provide a [mcve] that demonstrates the problem in action. – Remy Lebeau Mar 23 '22 at 08:39
  • it worked by using getline(cin>>ws,name[count}); i cannot figure out the purpose of "ws". – MINAAM AHMAD Mar 29 '22 at 07:21
  • @MINAAMAHMAD [`std::ws`](https://en.cppreference.com/w/cpp/io/manip/ws) simply reads and discards whitespace (spaces, tabs, line breaks, etc) from an input stream. – Remy Lebeau Mar 29 '22 at 08:23