string find question

A

alacrite

With this testprogram:

#include <iostream>
#include <string>

using namespace std;


int main()
{
string::size_type idx;
string s1;
string helloStr("hello");

cout<<"Enter a string ";
cin>> s1;
idx = s1.find(helloStr);

if(idx == string::npos)
cout<<"The string "<<helloStr<<" was not found in s1"<<endl;
else
cout<<"The first occurance of 'hello' in s1 is at: "<<idx<<endl;

string s2("This is a test hello world!");

idx = s2.find(helloStr);

if(idx == string::npos)
cout<<"The string "<<helloStr<<" was not found in s2"<<endl;
else
cout<<"The first occurance of 'hello' in s2 is at: "<<idx<<endl;

}
Program output:

Enter a string This is a test hello world!
The string hello was not found in s1
The first occurance of 'hello' in s2 is at: 15

Question why does it not find hello fo s1?
 
D

Daniel T.

With this testprogram:

#include <iostream>
#include <string>

using namespace std;


int main()
{
string::size_type idx;
string s1;
string helloStr("hello");

cout<<"Enter a string ";
cin>> s1;

cout << "s1 contains the string: " << s1 << '\n';
idx = s1.find(helloStr);

if(idx == string::npos)
cout<<"The string "<<helloStr<<" was not found in s1"<<endl;
else
cout<<"The first occurance of 'hello' in s1 is at: "<<idx<<endl;

string s2("This is a test hello world!");

idx = s2.find(helloStr);

if(idx == string::npos)
cout<<"The string "<<helloStr<<" was not found in s2"<<endl;
else
cout<<"The first occurance of 'hello' in s2 is at: "<<idx<<endl;

}
Program output:

Enter a string This is a test hello world!
The string hello was not found in s1
The first occurance of 'hello' in s2 is at: 15

Question why does it not find hello fo s1?

Add the line I put above and try running your program again.

Alternatively, replace the line "cin >> s1;" with "getline( cin, s1 );"
 
J

Jim Langston

With this testprogram:

#include <iostream>
#include <string>

using namespace std;


int main()
{
string::size_type idx;
string s1;
string helloStr("hello");

cout<<"Enter a string ";
cin>> s1;

This will only input characters to s1 until the first white space (tab or
space or enter).

use
std::getline( std::cin, s1 );
to get the whole text upto the carriage return.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top