Originally Posted by
Foley
ie, I want to a certain thing to happen if the user enters a certain string.
It's easy if you want an exact match. Just compare the string variable with a quoted string.
Code:
#include <iostream>
#include <string>
using std::cout;
int main()
{
std::string command;
cout << "Do you want a <greeting> or do you want to <quit>: ";
if (cin >> command)
{
if (command == "greeting")
{
cout << "Hello!\n";
}
else if (command == "quit")
{
cout << "Goodbye\n";
}
else
{
cout << "I don't understand\n";
}
}
return 0;
}
It's probably better to search for a substring though, that way if you type in some spaces or something, the messages still work.
Code:
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main()
{
string command;
cout << "Do you want a <greeting> or do you want to <quit>: ";
if (getline(std::cin, command))
{
if (command.find("greeting") != string::npos)
{
cout << "Hello!\n";
}
else if (command.find("quit") != string::npos)
{
cout << "Goodbye\n";
}
else
{
cout << "I don't understand\n";
}
}
return 0;
}