I 'm not quite sure if i did the right way but i just couldn't get the right value for my codes....can anyone figure out the problem?

for(int x = 0; x<myvector.size();x++)
	{
										
if(number.compare(0,2,myvector[x],0,2)==0) //compare number(user's input) to the line read from getline
		{		
		checknumber = true;		
		cout<<"passing compare++"<<endl;//if same number is found, then 	
				break;
				}
				else 							
				no++;				           
                             cout<<myvector[x]<<"value of myvector"<<endl;		
				}

Recommended Answers

All 4 Replies

Is that trying to compare the first two characters of each std::string? if( number.substr(0,2) == myvector[x].substr(0,2))

yea so why it isn't working?

if(number.compare(0,2,myvector[x],0,2)==0)

and should i use ?

if( number.substr(0,2) == myvector[x].substr(0,2))

>>yea so why it isn't working?


It does work. Since you didn't post the contents of that vector we have no idea what your program is comparing. compare() is case sensitive -- "Now" is not the same thing as "now" or "NOW".

Myself I would use the substr() approach, but compare() is ok too. So it boiles down to personal preference.

int main()
{
    vector<string> myvector;
    myvector.push_back("Now is the time");
    myvector.push_back("for all good men");
    myvector.push_back("to come to the aid");

    string number = "for";
    int x = 1;
     if( number.compare(0,3,myvector[x],0,3) == 0 )
         cout << "Yes\n";
     else
         cout << "No\n";

}

alright, thanks for the help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.