简体   繁体   中英

does function find in strings in c++ work only with the first char?

I want to find a char in a string consists of numbers and chars , if it's found the program does some operations , but when I use function find() , it returns only true if the char I am looking for is ONLY at the beginning of the string !!!!!

Ex : This is part of the problem !
The user enters 3 strings s1 , s2 , s3 ; between the first 2 strings there's char 'a' = '+' and between s2 and s3 there's char 'b' = '=' (The 3 strings are supposed to be numbers ) but if s2 is a word that includes the letter 'm' , the program converts s1 and s3 into integeres and writes the full operation ex : if i/p is 3247 + 5machula2 = 3749 then o/p would be 3247 + 502 = 3749

Here's the problem I'm trying to solve http://www.spoj.com/problems/ABSYS/ and this part of my code which has the problem :

int T;
int x,y,z;
string s1 ;
string s2  , s3 ;
char a , b;
cin>>T;
for(int i=0 ; i<T ; i++)
{
         cin>>s1>>a>>s2>>b>>s3;


for (int k=0; k<s2.size(); k++)
{ 
    if (k==s2.find("m"))
    {     
        stringstream ss(s1);
        stringstream ss3(s3);

        ss>>x;
        ss3>>z;

        cout<<s1<<" "<<a<<" "<<z-x<<" "<<b<<" "<<s3<<endl;
    }   
    else break;       
}

This is a loop that loops on the second string and if it find a char 'm' it should do what's mentioned above , but the problem here is that it only works if 'm' is at the beginning of the string and no place else.

Your else break; prevents the loop from ever looping.

The reason it only works when it's at the beginning is because you break out of the loop if it isn't, so it has no chance to check the rest:

[first iteration]
if (0 == s2.find("m")) //if found at beginning
    //do stuff
else break; //exit loop if not found at beginning

Instead of the loop, if you're just trying to see whether there is an m, just use find() :

if (s2.find('m') != std::string::npos)
    //"m" found in string, do the operations on s1 and s3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM