How to write C++ code that takes n strings and stores them inside a vector of strings and later prints it

85 Views Asked by At

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.

2

There are 2 best solutions below

1
Jakob Guldberg Aaes On

Explanation

I see the issue you're encountering. It's related to the interaction between cin and getline. After using cin to read n, it captures the number but doesn't remove the newline character from the input buffer. This causes the subsequent getline to read an empty string. To bypass this, it's good practice to clear the input buffer right after reading n.

Code

#include <iostream>
#include <vector>
#include <string>
#include <limits>

int main()
{
    int n;
    std::cin >> n;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // Clearing the input buffer

    std::vector<std::string> v;
    for (int i = 0; i < n; i++)
    {
        std::string s;
        std::getline(std::cin, s);
        v.push_back(s);
    }

    for (int i = 0; i < n; i++)
    {
        std::cout << v[i] << '\n';
    }
}

This should resolve the issue.

0
JW Yap On

Explanation

You would get just a newline if you call getline() immediately after cin >> n;. To avoid this issue, your would need to consume the newline first. You can do that by adding this before your for loop.

Code

cin.ignore();