-1

I want to search for a second string in a first string, by get strings from the user. But cin doesn't work for sentences because of spaces. How can I get a string as a sentence and then search for a second string in that sentence?

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    string str;
    cin>>str;
    string target;
    cin>>target
    char *p = strstr(str, target);

    if (p)
        cout << "'" << target << "' is present in \"" << str << "\" at position " << p-str;
    else
        cout << target << " is not present \"" << str << "\"";

    return 0;
}

https://onlinegdb.com/S1IVrTVHO

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Pary
  • 1
  • 2

2 Answers2

1

But cin doesn't work for sentences because of spaces.

std::cin is not the one that cares about spaces, operator>> does. Simply use std::getline(cin,str) instead of cin >> str when reading the sentence.

Also, you should be using std::string::find() instead of strstr().

Try this:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    getline(cin, str);

    string target;
    cin >> target;

    string::size_type p = str.find(target);
    if (p != string::npos)
        cout << "'" << target << "' is present in \"" << str << "\" at position " << p;
    else
        cout << "'" << target << "' is not present in \"" << str << "\"";

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

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!