Hello,
I am trying to use the find function to find when there is a period in a sentence.
The code I have written always finds a period even when there is not one.
1 2 3 4 5 6 7 8 9 10 11 12 13
{
bool found=false;
cout<<"Enter a sentence: "<<endl;
cin>>sentence;
{
if (found=sentence.find('.',0));
found=true;
}
if (found=true)
{
cout << "Period found"<<endl;
}
}
For some reason it skips over my find code and goes strait to the cout?
one last thing I tried to add the word "stop" to find, it finds it if it is not entered with a period '.' but when I try to find "stop." it only finds '.'
My code now only outputs if stop or period are found but not if they are not found why will it not display the not found if it does not find a period or the word stop?
I added the find function to say where "stop" was found or where '.' was found, but then I noticed it would not allow me to input sentences, so I change the cin to getline and now it skips over all my code?
{
bool pfound=false;
bool sfound=false;
cout<<"Enter a sentence: "<<endl;
getline(cin,sentence);
std::size_t found=sentence.find('.');
{if (sentence.find('.') != std::string::npos)
pfound=true;
if (pfound)
cout << "The character '.' is located at index "<<found<<endl;
else
cout<<"Your sentence does not contain the character '.'"<<endl;
}
std::size_t found1=sentence.find("stop");
{if (sentence.find("stop")!= std::string::npos)
sfound=true;
if (sfound)
cout<<"The word "<< "stop"<<" starts at index "<<found1<<endl;
else
cout<<"Your sentence does not contain the word "<< "stop"<<endl;
}
}
It can find '.' and/or "stop" now in a sentence, but the location it gives is incorrect. why would the getline change how it computes the location of what its looking for?
{
bool pfound=false;
bool sfound=false;
cout<<"Enter a sentence: "<<endl;
((cin >> sentence).get() && std::getline(cin, sentence));
std::size_t found=sentence.find('.');
{if (sentence.find('.') != std::string::npos)
pfound=true;
if (pfound)
cout << "The character '.' is located at index "<<found<<endl;
else
cout<<"Your sentence does not contain the character '.'"<<endl;
}
std::size_t found1=sentence.find("stop");
{if (sentence.find("stop")!= std::string::npos)
sfound=true;
if (sfound)
cout<<"The word "<< "stop"<<" starts at index "<<found1<<endl;
else
cout<<"Your sentence does not contain the word "<< "stop"<<endl;
}
}