954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Find character in string

I wonder something about finding a specific character in a string.
What I am trying is to find "*" and if that character is found in the string, I will
write "Found" to a file.
When running the code below. All this is happening but the same thing is happening
if I change the string1 to "Number1 - Number2".
So I wonder if I could have missed anything here ?

ofstream File1;
File1.open("C:\\File1.txt");

std::string string1 = "Number1 * Number2";

if( string1.find("*") )
{
    File1 << "Found";
}
Jennifer84
Posting Pro
564 posts since Feb 2008
Reputation Points: 10
Solved Threads: 1
 

You have to check against std::string::npos the return value of the find() method.

std::string::size_type pos = string1.find("*");

if(std::string::npos != pos)
{
    // found a match at 'pos'
}
else
{
    // not found
}


For information on std::string::npos see http://www.cplusplus.com/reference/string/string/npos.html

mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
 

this is because:
Return Value for string.find(...) is:
1) The position of the first occurrence in the string of the searched content.
or
2) If the content is not found, the member value npos is returned.

so your if(...) always evaluates to true.

ninjaneer
Junior Poster in Training
56 posts since Jun 2008
Reputation Points: 10
Solved Threads: 6
 

Yes this was the problem. Thank you,
I will experiment with this.

this is because:
Return Value for string.find(...) is:
1) The position of the first occurrence in the string of the searched content.
or
2) If the content is not found, the member value npos is returned.

so your if(...) always evaluates to true.

Jennifer84
Posting Pro
564 posts since Feb 2008
Reputation Points: 10
Solved Threads: 1
 

Added post by mistake, sorry.

dpreznik
Light Poster
38 posts since Jul 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You