MINAAM AHMAD
MINAAM AHMAD

Reputation: 1

Array of string type

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];

Upvotes: 0

Views: 109

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595602

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

Upvotes: 2

Related Questions