ive a little question. how do I know if a given word in a sentence, so I then can perform an action?
Example: this is an example
check the word: example
now if example is found i what to run some code. Does anybody know how to solve this?
First, read a whole line into a std::string and get rid of any character that isn't a letter. This will keep you from reading something like "example." as if it were a word. Do notice that this prevents the program from reading words with the character '-' in them, so adjust as needed.
Then, parse the buffer using a std::stringstream and check for the word you're looking for. In this case, we simply output the word and break from the loop, but in a real program this should really be inside a function, something like bool f(std::string line, std::string word) that would return if it found the word.
One last thing: this really has nothing to do with Windows so I guess it doesn't fit the Windows programming forum.
This solution is based on the use of a standard string function strstr( char* s1, char* s2) which returns a pointer to the location of s2 within s1. It is a console app (not a windows app).
I have initialized a char* to NULL here. If it stays NULL it is because the word was not found within the sentence. Note: As written the sentence length is limited to 49 characters so adjust if needed for a longer one.
#include <iostream>// for use of cin, cout
#include <cstdio>// for use of gets(), scanf()
#include <cstring>// for use of string functions strcpy(), strcmp(), strlen(), strcat(), strstr(), etc.
usingnamespace std;
int main()
{
char bigString[50];
char word[50];
char* pLocation = NULL;
char a = 'n';
do // allows program to repeat without restart
{
cout << "enter big string:";
gets_s(bigString);
cout << "enter a word:";
gets_s(word);
pLocation = strstr(bigString, word);// this string function returns pointer to 2nd string within 1st
if( pLocation == NULL )
cout << word << " is not in the sentence: " << bigString << endl;
else
cout << word << " is in the sentence: " << bigString << endl;
cout << "repeat (y/n)?" << endl;
scanf_s("%c", &a);
_flushall();
pLocation = NULL;// reset for next loop
}while( a=='y');// if anything other than 'y' is entered program will terminate
return 0;
}
Are you trying to create the functionality of the strstr() function yourself? If so then this "solution" misses the point of your exercise.