How to write C++ code that takes n strings (can have space between) and store them inside a vector of strings and later prints it? (Taking the strings inside a vector is necessary.)
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<string> v;
for (int i = 0; i < n; i++)
{
string s;
getline(cin, s);
v.push_back(s);
}
for (int i = 0; i < n; i++)
{
cout << v[i] << endl;
}
}
This is my code. It is only taking n - 1 strings instead of taking n strings. Then it is printing a new line and then printing the n - 1 strings.
Explanation
I see the issue you're encountering. It's related to the interaction between
cinandgetline. After usingcinto readn, it captures the number but doesn't remove the newline character from the input buffer. This causes the subsequentgetlineto read an empty string. To bypass this, it's good practice to clear the input buffer right after readingn.Code
This should resolve the issue.