I was curious to know that how can I make my code dynamic like when a user gives some input like 'switch on TV' then it will not be limited to that string but it can be dynamic like 'turn on the tv' or 'can you please turn on the tv'.
Please help I'm a begginer.
Having a computer parse English is incredibly complex to do right... I mean, cell phones and other cylindrical spyware devices can do it well enough, but still only based on relatively simple commands.
At this point, I would just make it so the program can detect certain combinations of keywords. e.g. if the word contains both "on" and "tv".
// Example program
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
#include <algorithm>
enumclass Action {
Unknown,
TV_off,
TV_on,
};
enumclass NullableBool
{
Null,
Off,
On
};
usingnamespace std;
string to_lower(string str)
{
std::transform(str.begin(), str.end(), str.begin(),
[](unsignedchar c){ return std::tolower(c); });
return str;
}
Action parse(const std::string input)
{
bool tv = false;
NullableBool turn_on = NullableBool::Null;
istringstream iss(input);
string word;
while (iss >> word)
{
string lower = to_lower(word);
if (lower == "tv")
{
tv = true;
}
elseif (lower == "on")
{
turn_on = NullableBool::On;
}
elseif (lower == "off")
{
turn_on = NullableBool::Off;
}
}
if (tv && turn_on == NullableBool::On)
{
return Action::TV_on;
}
elseif (tv && turn_on == NullableBool::Off)
{
return Action::TV_off;
}
else
{
return Action::Unknown;
}
}
int main()
{
cout << "What should I do?\n>";
string input;
getline(cin, input);
Action act = parse(input);
switch (act)
{
case Action::TV_on:
cout << "Okay. Turning the TV on.\n";
break;
case Action::TV_off:
cout << "Okay. Turning the TV off.\n";
break;
default:
cout << "I didn't quite get that.\n";
break;
}
}
What should I do?
>Turn TV off
Okay. Turning the TV off.
What should I do?
>turn on tv
Okay. Turning the TV on.
What should I do?
>I hope you malfunction
I didn't quite get that.
1 2
cin >> input;
if (input == "switch on TV" ||
Note you'd have to use getline(cin, input); here if you want the string to contain spaces.
Edit: As Niccolo said, if you're an absolute beginner, even just parsing a string like this could seem overwhelming. I would just stick to more simple stuff, follow books/tutorials first. [Not that I'm implying that my example is really that complex. But if you start trying to add different commands and more dynamic phrases to it, it will blow up in complexity.]