C++ command line prompt shouldn't repeat

My program takes input from the command line, and should be able to process both single and multiple character commands like this:

prompt> A  
A response
prompt> AB  
A response  
B response  

But right now my program behaves like this:

prompt> AB
A response
prompt>
B response

How can I structure the loop to fix this?
Right now I have:

for(;;)
  cout << prompt
  cin >> command
  // error checking
  switch(command) { ... }

2 answers

  • answered 2018-10-09 16:33 R Sahu

    How can I structure the loop to fix this?

    One way to do that would be to:

    1. Read the input as a token.
    2. Iterate over the characters of the token
    3. Process each charater as you see fit.

    std::string token;
    std::cout << prompt;
    std::cin >> token;
    for ( char command : token )
    {
       switch(command) { ... }
    }
    

    If you would like to be able treat white space characters as commands, it will be necessary to use std::getline to read a line of text and iterate over the characters of the line.

    std::string line;
    std::cout << prompt;
    std::getline(std::cin, line);
    for ( char command : line )
    {
       switch(command) { ... }
    }
    

  • answered 2018-10-09 16:46 pm100

    assuming command is declared as a char your code is doing exactly what you say.

    for(;;)
      cout << prompt // prompt user types AB
      cin >> command  // read one char A
      // error checking
      switch(command) { ... } // process it
    }
    

    Now loop back and reprompt.

    You need

    for(;;)
    {
      cout << prompt
      cin >> commandString // std::string
      for(auto command : commandString) // loop over each char
      {
       switch(command) { ... }
      }
    }