0
int main()
{
    int noOfInput; 
    std::cin >> noOfInput;
    try
    {
        std::getline(std::cin, line);
        auto start = line.find_first_not_of(" ");
        auto stop = line.find_first_of(" ", start);
        int quantitiy = std::stoi(line.substr(start, stop - start));
    }
    catch (const std::logic_error & ex)
    {
        std::cout <<"Logic Error: " << ex.what() << std::endl;
    }
}

Running the above code with the following input:

4
1 book at 14.49
1 shirt at 19.99
1 chocolate bar at 1.00
1 clearance chocolate bar at 2.00

I am getting exception just after entering my No of inputs:

Logic Error: basic_string::substr: __pos (which is 18446744073709551615) > this->size() (which is 0)

What's wrong with my code?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Falcon
  • 37
  • 3
  • Please show a [mre] within the question without relying on external links. Have you tried using a debugger or even printing `what` from the exception? – Alan Birtles Jul 18 '22 at 06:15
  • 1
    The first time through your loop `line` is empty, this causes `find_first_not_of` to return `std::string::npos`, passing `npos` as the first argument to `substr` causes the logic error `basic_string::substr: __pos (which is 18446744073709551615) > this->size() (which is 0)`. You should always check the results from functions like `find_first_not_of`. – Alan Birtles Jul 18 '22 at 06:33
  • So how to handle the first time when line is empty. – Falcon Jul 18 '22 at 13:35
  • see the linked duplicate – Alan Birtles Jul 18 '22 at 14:38

0 Answers0