2

I am trying to do some string and vector operations, I want my for loop to execute n times but it terminates executing n-1 lines. suppose I gave input for the number of loops to be 5, it executes till 4 only times and terminates.;

this is my code which gives error;

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
    int number_of_loop;
    vector<string>p;
    string elem;
    cin>>number_of_loop;
    cout<<"enter your strings for  loop now:";
    for(int i=0;i<number_of_loop;i++){
        getline(cin, elem);
        p.push_back(elem);
    }
    string y=p[0];
    cout<<"output are being printed"<<endl;
    cout<<y<<endl;
    cout<<y[1]<<endl;
    cout<<p[1][0]<<endl;
}

but this below code works perfectly fine where I have initialized number of loops before itself;

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
    int number_of_loop=5;
    vector<string>p;
    string elem;
    cout<<"enter your strings for  loop now:";
    for(int i=0;i<number_of_loop;i++){
        getline(cin, elem);
        p.push_back(elem);
    }
    string y=p[0];
    cout<<"output are being printed"<<endl;
    cout<<y<<endl;
    cout<<y[1]<<endl;
    cout<<p[1][0]<<endl;
}

what goes wrong with my first code, please do help, thanks a lot.

def __init__
  • 1,092
  • 6
  • 17
  • 1
    `cin>>number_of_loop;` reads the integer but leaves the Enter in the input buffer. Thus, the first `getline(cin, elem);` reads this Enter (as an empty string). (Check this in the debugger to prove me right.) To overcome this, you could insert an [cin.ignore(std::numeric_limits::max())](https://en.cppreference.com/w/cpp/io/basic_istream/ignore) after the `cin>>number_of_loop;`, – Scheff's Cat Jul 01 '21 at 18:49

0 Answers0