0

I'm trying to create substrings from my from each line of my input file.

I noticed that when i create a substring from substr(0,2) position zero it prints out correctly but if I start from anywhere greater than 0 it throws this error:

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string

and Im also reading in lines in this format 40AF FF A9

int main() 
{
  string STRING;
  ifstream infile;
  infile.open("test-file.txt");
  while(!infile.eof())
  {
     getline(infile, STRING);
     string tag = STRING.substr(2,2);
     cout << tag << endl;
  }
  return 0;
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Jason Yao
  • 3
  • 1
  • 2
    Can we see a chunk of the test-file.txt? (not just the format) Add it to the question, not a comment, pls. – belwood Jul 19 '15 at 00:54
  • You should always check the size of the string before performing a substring operation. What if, for example, you have a blank line? – Michael Aaron Safyan Jul 19 '15 at 00:55
  • 1
    You check before reading instead of after reading! Use `while (std::getline(infile, STRING))`. Also, you need to have at least 4 character in the string for your `STRING.substr(2, 2)` to succeed. You should verify that this is the case (with your current setup you'll get undefined behavior after the last line). – Dietmar Kühl Jul 19 '15 at 00:58

1 Answers1

0

The substr() method is defined as follows, in the C++ standard:

21.4.7.8 basic_string::substr [string::substr]

basic_string

 substr(size_type pos = 0, size_type n = npos) const;

 1 Requires: pos <= size()

 2 Throws: out_of_range if pos > size().

So, the pos parameter, the first parameter to the substr() method, must be less than or equal to size(), the size of the std::basic_string class instance.

You are passing "2" for the "pos" parameter, so this method will throw an exception if the length of your string is less than 2 characters.

If your code reads an empty line from the file, the string's size() will be less than two, and your code will throw an exception.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148