title: Extracting a random word in a string
body: <p>I would like to extract a random in a given line so I called a random number to use it as an index. But it keeps giving me an error.</p>
  
  <pre><code>terminated called after throwing an instance of 'std::out_of_range'.
  </code></pre>
  
  <p>I know it occurs because the index value is exceeded size of the string. But I can not find any mistake in my code.</p>
  
  <pre><code>do {
      int size = line.length();
      srand(time(NULL));
      index = rand() % size;
  } while (isspace(line.at(index)));
  </code></pre>
  
  <p>This is a random number generator. I extract a line from a text file.</p>
  
  <p>I used
      do { } while (isspace(line.at(index)));
  because I do not want it to be space, in order to generate a random number again if it is space. </p>
  
  <p>What I want is this.</p>
  
  <p>0123456789</p>
  
  <p>Example...        Index : 4</p>
  
  <p>F---i----L        F : First, L : Last</p>
  
  <pre><code>if (index == 0) {
      while (!isspace(line.at(last + 1))) {
          last = last + 1;
      }
  }
  
  else if (index == (size - 1))) {
  
      while (!isspace(line.at(first - 1))) {
          first = first - 1;
      }
  }
  
  else {
      while (!isspace(line.at(first - 1))) {
          first = first - 1;
      }
  
      while (!isspace(line.at(last + 1))) {
          last = last + 1;
      }
  }
  
  for (int i = first; i &lt;= last; i++) {
      targetword += line.at(i);
  }
  </code></pre>
  
  <p>This is how I calculate first and last index and print out the chosen word and it should not make any error...</p>
  
  <p>please help me thank you</p>