Std::out_of_range error when using substring C++

Asked

Viewed 126 times

-1

I have a file txt containing the following type of information on each line:

Example:

John-88888888

I need to read every line of that file and separate the name in a variable and the number in another, I used the substring(), to get the name I did the following.

 while(!temp.eof()){       
        getline(temp, linha); 
        posl = linha.find('-');
        if((linha.substr(0, posl).compare(nome))){
          //faço algo aqui
        }
 }

So the algorithm works perfectly and I take only the name that exists on the line and compare it with another variable and perform an operation there. But I’m making a mistake when I try to get the number. Code:

 while(!temp.eof()){
      getline(temp, linha);
      posl = linha.find('-');

      if(linha.substr(posl+1).compare(numero)){ //aqui quebra
           //faço algo
      }
 }

The mistake is this

terminate called after Throwing an instance of 'Std::out_of_range'

With more information. The variable types are correct. What is causing this? Is there another way more practical?

2 answers

1

Only with this information can not help much. Missing parts of the code, we do not have the data that produce this, nor details of the error.

The code looks strange in the two parts shown. For example, the compare is used in an abnormal way, I hope you know what you are doing. But this does not generate this error.

You probably can’t find the hyphen on the line and the posl (terrible variable name to read in the code, confuses the letter L with the number 1) is worth a very high value. When you add 1 to it and try to access one of the characters, it gives this error. The high value outside the acceptable range for this text was generated because the find didn’t find what he was looking for.

0


In c++, the substr method returns an out_of_range exception if the user tries to use the method with values that are larger than the string size (See end of Reference c++ on the substr method)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.