Hey everyone, this is my first post here, and I'm new to programming. This is what I'm trying to do. "Create a function that takes parameters of two character arrays (sentence and word), two integers of their lengths, return to the 1 if the word is in the sentence; returns -1 otherwise." This is an assignment by my teacher. I'm not sure how to return a 1, or a -1 if the word is found. Help?
Normally, I would try and use code that easier. (Who wouldn't?) Unfortunately, my class is intro level, so we can only use iostrea, and cstdio functions. :/
Okay, so I didn't solve this problem correctly haha. THis is what we are supposed to do. ""create a function that takes parameters of two character arrays (sentence and word), two integers of their lengths, return to the 1 if the word is in the sentence, return -1 if otherwise"
But we aren't actually printing out a 1 or -1. The 1 or -1 determins what message should appear aat the end. 1 = the word is in the sentence, -1 = the word is not in the sentence"
here's my code.
#include <iostream>
#include <cstdio>
using namespace std;
int printsomething (char sentence [], char word [], int len, int lenS);
int printsomething (char sentence [], char word [], int len, int lenS)
{
bool match = false;
for (int i=0; i<len-lenS+1 && !match; i++)
{
if(sentence[i] == word[0])
{
match = true;
for(int j=1; j<lenS && match; j++)
if(sentence[i+j] != word[j])
{
match = false;
}
}
}
for (int i = 0; word[i] != '\0'; i++)
cout << word[i];
int found=printsomething(sentence, word, len, lenS);
if (found==1)
if (match)
{
return 1;
}
return -1;
}
int main()
{
char sentence[100];
char word[25];
cout << "Type a sentence:\n";
gets_s(sentence);
cout << "Type a word:\n";
cin >> word;
int len = strlen(sentence);
int lenS = strlen(word);
printsomething(sentence, word, len, lenS);
system("PAUSE");
return 0;
}
Everytime i run it, it give me infinite copies of whatever word I searched.