str.replace()

I'm trying to make code that writes code based on a two text files and user input, but I'm having issues with one line of it. I'm trying to replace a certain section of my string with another, but since I don't know what's going to be in either string, I have to use variables to do this. I'm using str.replace(), but whenever the application tries to read that line of text, it gives me a warning about shutting down Runtime.

This is where the code becomes a problem.
1
2
3
4
5
6
7
if(input.find(keywords[find], 0) >= 0)
{
	replacePos = input.find(keywords[find], 0);
	keyLength = keywords[find].length();
	replacement = replace[find];
	input.replace(replacePos, keyLength, replacement);  //this is where the code becomes a problem
}


This is what the console does with this part of the code.
Enter file name:  test code
Enter title:  test code
Enter description:  test my code

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Press any key to continue . . .
You aren't checking the return from string::find() to see if it's valid.

Maybe you should be.

if(input.find(keywords[find], 0) >= 0)

Not sure if I read that correctly, but it seems like I'm making sure that the position is not a negative number.

It already checks to make sure there is a keyword in the string. Otherwise it won't pass at all.

EDIT: I don't mean to be offensive, but I already made sure that it would find a word to replace before continuing. I didn't want it to replace something that isn't there to be replaced. The code was a little different before. I had to create those three new variables to try to fix it and it's still only that one line.
Last edited on
I don't want to dump my whole code because that would be a waste of space, but I can do that if anyone needs the rest to find the problem.
Like I said, you're not checking to see if the return value from string::find() is valid.

http://www.cplusplus.com/reference/string/string/find/
The return from std::string::find() is size_t which is an unsigned int. That means that it is never less than zero.
You should use:
 
if(input.find(keywords[find], 0) != std::string::npos)
This works, thanks. Sorry for my irritation. My c++ book says that it returns a negative number if the string I'm looking for is not in the string I'm searching.
These are not the droids you are searching for.
Topic archived. No new replies allowed.