I get the error at the for loop.
You should describe the error you get. I happen to have access to Xcode so I can run your code and see what happens, but you should try to spare that of people from whom you want help.
In this case you should describe how the debugger stops the program at the line:
char ch_4 = text.at(i + 3);
includes the message: "Thread 1: signal SIGABRT" and the console output shows
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
Your problem is this: the for
loop checks to make sure that i
is in the correct range for the string text
before using it as an index, but then you also use i+1
, i+2
, and i+3
as indices without checking that those values are also valid.
Fix that check and the program appears to run fine (given correct input).
Some miscellaneous comments.
- Use more consistent indentation. It makes the program easier to read and follow. Here's how I would indent it (using the tool clang-format).
#define SPACE ' '(char)
looks like a bad idea, even if you're not using it.using namespace std;
is usually frowned on, though as long as you don't put it in headers it usually won't cause too much trouble. I still could though, and because you probably won't understand the resulting error message you may want to avoid it anyway. If you really don't like writingstd::
everywhere then use more limited applications such asusing std::string;
andusing std::cout;
.- global variables should be avoided, and you can do so here by simply passing
textUserSubmit
andwordUserSubmit
tosearchWord()
. - there's really no need to make sure
text
is less than or equal to 500 characters in length. You're usingstd::string
, so it can hold much longer input. - You never check how long
word
is even though your code requires it to be at least 4 characters long. Fortunately you're usingat()
to index into it so you don't get undefined behavior, but you should still check. I'd remove the check intextQuery
and add one towordQuery
.