Error 'std :: out_of_range' when using C ++ substring

-1

I have a txt file that contains the following information in each line:

Example:

  

John-88888888

I need to read each line of this file and separate the name in one variable and the number in another, for that 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
        }
 }

In this way the algorithm works perfectly and I get only the name that exists on the line and compare it with another variable and perform an operation there. But I'm having an error 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 error is this

  

terminate called after throwing an instance of 'std :: out_of_range'

with more information. Variable types are correct. What is causing this? Is there another more practical way?

    
asked by anonymous 24.08.2015 / 02:03

2 answers

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 the end of c ++ reference on the substr method)

    
24.08.2015 / 02:50
1

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

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

You probably are not finding the hyphen on the line and the posl (bad 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 find did not find what it was looking for.

    
24.08.2015 / 02:17