Home > Mobile >  C read multiple optional inputs from std::cin
C read multiple optional inputs from std::cin

Time:11-08

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?

CodePudding user response:

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;
      // ...
    }
  // ...
  }
}
  •  Tags:  
  • c
  • Related