Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ read multiple optional inputs from std::cin

While trying to generate a simpleVM for learning C++, I faced following Problem:
So lets assume I want and Input of 10 C 222, where 10 would be the opcode (movi in this case), C a register and 222 a value. Thus 10 C 222 would store 222 into register C.
To get some Input, I am currently using

int runVM(){
  int i, v; //opcode i, Value v
  char n; //Register

  while (true) {
    std::cin >> i >> n >> v;
     

   switch (i) {
      case 0:
        return C;
      case ...
    }

However, this only allows me to enter 3 inputs. Not less. With the opcode of 0, my VM would close and return C, so no input Register or Value is needed. Currently I still need to enter 0 0 0 to return and break the loop.
Is there any function in C++ that allows me to expect 1, 2 or 3 ińputs and uses a default (empty value) when simply pressing enter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One choice is to read the opcode and then decide what else needs to be done. This looks like

int runVM(){
  int i, v; //opcode i, Value v
  char n; //Register
  int C = 1; // undefined in OP

  while (true) {
    std::cin >> i;

    switch (i) {
      case 0:
        return C;
      case 10:
        std::cin >> n >> v;
        // do something
        break;
      // ...
    }
  // ...
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading