Continuous Input

I've set up the following code to accept the strings "hello", "reverse" and "quit".

"hello" will print out "Hello, World!"
"reverse" will ask for another string input which it will then reverse
"quit" will print out "Goodbye!" and end the program.

However, the code is set up to take a command, execute, and then quit.

How do i get it to continue accepting commands until I ctrl+c or enter "quit"?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>

using namespace std;

void reverseChar(char* str) {
     std::reverse(str, str + strlen(str));
     }

int main() {

     char input[8];
     char str[256];
     int i, n;

     cout << "> ";
     cin.getline ( input, 8 );

     if ( strcmp ( input, "hello" ) == 0 ) {
          cout << "Hello, world!" << endl;
     }

     if ( strcmp (input, "reverse" ) == 0 ) {
          cout << " > ";
          cin.getline ( str, 256);
          reverseChar(str) ;
          cout << " < " << str << endl;
     }

     if (strcmp ( input, "quit" ) == 0 ) {
          cout << "< Goodbye!" << endl;
     }

     return 0;
}
You've #include <string> ... why don't you use it? ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>

std::string reversed(const std::string& s)
{
    return std::string(s.rbegin(), s.rend());
}

int main() 
{
    std::string input;

    while (getline(std::cin, input) && input != "quit")
    {
        if (input == "hello")
            std::cout << "Hello world!\n";
        else if (input == "reverse")
        {
            std::string line;

            std::cout << "> ";
            getline(std::cin, line);
            std::cout << " < " << reversed(line) << '\n';
        }
        else
            std::cout << "Unrecognized command: " << input << "!\n";
    }
}
lol awesome! thanks!
Topic archived. No new replies allowed.