Hi :)

I am using basic replace function but getting some runtime error as below:-

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::replace

I already know the position where I should replace so don't need to find it. Can somebody tell me how to avoid this error ? :icon_evil:

Here is my code:-




#include <stdlib.h>

using namespace std;

int main(int argc ,char* argv[]){

       string line1;

	   ifstream myFile(argv[1]);

	   if(! myFile){

	      cout << "Error opening file" << endl;

		  return -1;


	   while(! myFile.eof()){

	       getline(myFile, line1);
			 line1.replace(10, 1, "W");
                         cout << line1 << endl;


    return 0;


Thanks ;)

I'd suggest trying to hardcode the values to see if there is something wrong with your input. I'd also suggest using <string> instead of <string.h>

This works fine for me:



int main(int argc ,char* argv[])

  std::string line1 = "Test 12345 Test 6789";
  std::cout << line1 << std::endl;
  line1.replace(10, 1, "W");
  std::cout << line1 << std::endl;

  return 0;


or probably the range i.e 10 you are puting, that number of characters are not there in the string that you want to replace.
so, just check the value of the string and debug it.

The header <string.h> is the pre-standard version of the standard <cstring> header. This header is used for manipulating C-style strings (null-terminated arrays of char).

To access the member functions of the built-in C++ string type, you need to use the header <string> instead.

What are the contents of the file you are trying to read? Do you know that the 11th character is within the range of the string you've read from the file? Don't forget, arrays have subscripts from 0 to (size-1).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.