ok it works when i type that in but what if the user just types fnsdjkfndskfnsfsjkd or just whatever they want, then it crashes, how do i avoid crashes? I was thinking something like this but i got an error:
1 2 3
if(input.find != "test"){
return 0;
}
error:
C:\Users\Chay Hawk\Desktop\C++ Testing\main.cpp||In function 'int main()':|
C:\Users\Chay Hawk\Desktop\C++ Testing\main.cpp|16|warning: comparison with string literal results in unspecified behaviour|
C:\Users\Chay Hawk\Desktop\C++ Testing\main.cpp|16|error: invalid operands of types '<unresolved overloaded function type>' and 'const char [5]' to binary 'operator!='|
||=== Build finished: 1 errors, 1 warnings ===|
Now you know why I put this bit in the code I posted.
1 2 3 4 5 6 7 8 9
size_t pos;
pos = input.find(wordToFind);
if (pos == string::npos)
{
cout << "** Error - Search string not found in input **" << endl;
}
the find function returns a value string::npos when it does NOT find the substring
you were searching for.
You should test for this condition BEFORE attempting to make the substitition.
Also what if i have like 10 or 15 words that i want found and changed?? i cant use a switch statement with strings and i dont really like nesting too many if statements, so what can i do??
I wouldn't worry too much about changing 10 or 15 words since you still haven't managed to get it to change one reliably.
The only way to reliably replace a substring using find and replace is to check the return value of find to see if the substring was found. Limiting your input to the substring you want to replace really isn't an option.