Fahmy Arsyaad Fahmy Arsyaad - 1 year ago 64
C++ Question

Finding String on C++

I got a task from my teacher. I try some code but it confuses me a lot. So here's my code :

#include <iostream>
using namespace std;

char inputChecker [1000];
string source = "10110111000111001101110";
string detected;

int main(){
cout <<"Input:";
cin >> inputChecker;
for (int i=0;i<source.size();i++){
if (source[i]==inputChecker[0]){
cout <<"Data " <<inputChecker <<"is exist" <<endl;
else if (source[i]==inputChecker[i]){
cout <<"Data " <<inputChecker <<" isn't exist'" <<endl;

So ,my expectation output is ,when i input 10,it will result "Data 10 is exist". Without looping. I think it needed 2 kind of looping but i dont know where to loop.

My expectation output :

Input : 10
Data 10 is exist

Input : 25
Data 25 isn't exist

Thanks before :))

Answer Source

No need for loop

#include <iostream>
using namespace std;

int main() {
    string source = "10110111000111001101110";
    string input;
    cin >> input;
    if (source.find(input) != string::npos)
        cout << input << " exists\n";
        cout << input <<" doesn't exist\n";

Have a look at other useful std::string methods like find_first_of, find_last_of, etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download