If you want to get a whole line, use getline()
which is in <string>
.
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
string target;
getline(cin, target);
const char* p = strstr(str.c_str(), target.c_str());
if (p)
cout << "'" << target << "' is present in \"" << str << "\" at position " << p - str.c_str();
else
cout << target << " is not present \"" << str << "\"";
return 0;
}
The .c_str
convert the std::string
to a C-Style string, so that strstr
, which only takes C-Style strings, can do it's operations. Also, in your original code, you forgot to terminate cin>>target
with a ;
.
std::cin
is where the input comes from. The >>
operator gets something from std::cin
until a whitespace. If you want a whole line, use std::getline(cin, str)
instead of cin >> str
. std::getline()
reads from std::cin
until it hits a newline, so it is better for your purposes. (std::getline
takes a istream
(like std::cin
) as its first parameter, and a std::string
to put its result as it's second parameter.)
Also, in the future, you might consider using other methods of finding strings in strings, and not use strstr()
, as that is for C-Style strings, and for more C++ style substring finding, there may be better alternatives.
Bye!