0

Currently doing a project at uni where at first I need to de-hyphenate a string, seemed pretty simple however when i run the program it has an error WeirdPuncProgram.exe: Microsoft C++ exception: std::out_of_range at memory location 0x004EF898

It also is not returning the string value properly, inside the function answer() is changed and hyphens are removed but once it comes out its just the original input again.

#include <iostream>
#include <string>

using namespace std;

string answer;

string hyphonRemover(string answer)
{
   string spacer = " ";
   int h;
   for (int i = 0; i < answer.length(); i++)
   {
      h = answer.find_first_of("-");
      answer.replace(h, 1, spacer);
   }
   return answer;
}


int main()
{

   cout << "Type a sentence which contains punctuation and ill remove it for you! " << endl << endl;
   getline(cin, answer);
   hyphonRemover(answer);
   cout << answer << endl;
   system("pause");
   return 0;

}
oarfish
  • 4,116
  • 4
  • 37
  • 66
  • 2
    You are not checking if `answer.find_first_of("-");` returns a negative number, which happens if no match is found. Using a negative index will cause trouble on the next line. – J.J. Hakala Jan 19 '16 at 11:42
  • 1
    Also, you call `hyphonRemover` and then throw away the result without storing it. – PeterT Jan 19 '16 at 13:00

1 Answers1

1

every use of answer in hyphonRemover() will be local variable, not global answer you defined above.

thus the function will modify only its local variable.

ehwank
  • 31
  • 1
  • 2