1

I want to input multi-word strings into vector "name". Using cin works fine for single word inputs. What i want is :

  1. Take number of string inputs from the user. for example : "Random Name"
  2. Store all the String value into the vector names

Here is the code i wrote

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

int main()
{
    vector<string> names;
    string user;
    int n;
    cout << "Enter number of Users : ";
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> user;
        names.push_back(user);
    }
    for (int i = 0; i < names.size(); i++)
    {
        cout << names[i] << " ";
    }
}

Problem: When i use getline() instead of cin in the for loop, it omits 1 input. For example , if the user inputs - Number of Users = 3, it only takes 2 string inputs

string user[n]; // value of n given by user using cin
for (int i = 0; i < n; i++)
{
    getline(cin, user[i]);
    names.push_back(user[i]);
}
R3VAMP
  • 13
  • 5

1 Answers1

2

Try this:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<string> names;
    string user;
    int n;
    cout << "Enter number of Users : ";
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> std::ws;
        getline(cin,user);
        names.push_back(user);
    }
    for (int i = 0; i < names.size(); i++)
    {
        cout << names[i] << " ";
    }
}
cin>>std::ws;

The issue here is that the compiler is considering the newline after you are entering the number of inputs, and pressing enter. So, the fix is to extract the additional whitespaces. Check http://www.cplusplus.com/reference/istream/ws/

Suyash Krishna
  • 241
  • 2
  • 8
  • Good answer. You only need one `cin >> std::ws` here though so you could do it before the loop: `cin >> n >> std::ws;` – Ted Lyngmo Mar 25 '21 at 07:06
  • So, is this same as cin.ignore() as ignore() does the same work ? Any usecase would be helpful – R3VAMP Mar 25 '21 at 08:14