1

I am getting this error when I am running -

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr As suggested in this post(http://www.cplusplus.com/reference/string/string/getline/) , to read a line in c++, we use std::getline (std::cin,name); My code is :

   int t;
    cin>>t;
    while(t--)
    {
        string s;
        int num;
        getline(std::cin,s);
        string q= s.substr(0,3);
        num  =stoi(s.substr(4));
    }

When I run only this:

    string s;
    int num;
    getline(std::cin,s);
    string q= s.substr(0,3);
    num  =stoi(s.substr(4));

It works. I think I have to flush my cin buffer. What should be the best practice for these type of cases? Thanks in advance

P0W
  • 42,046
  • 8
  • 62
  • 107
Ayush Shukla
  • 117
  • 10
  • Best practice for the `>>t` is to flush the input buffer after, e.g. via `ignore`. Best practice for the `substr` is to make sure of the string length first. – Cheers and hth. - Alf Aug 02 '15 at 05:03
  • Yes and it works fine when just after the while loop, I write `std::cin.ignore(INT_MAX);`. So every time should I write like this? Isn't there any better approach? – Ayush Shukla Aug 02 '15 at 05:05
  • Usually you only want to consume through the newline left after your formatted numeric input. `std::cin.ignore(std::numeric_limits::max(), '\n');` Discussed in-detail [in **this** question](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction). – WhozCraig Aug 02 '15 at 05:39

0 Answers0