int chooseWallet() { std::string selection; std::cout << "Which wallet are you using?" << "(Cash, Credit, Debit)" << std::endl; printPrompt(); while (getline(std::cin, selection)) { if (std::cin.fail()) { std::cin.clear(); std::cout << "Incorrect input, please try again" << std::endl; printPrompt(); continue; } std::transform(selection.begin(), selection.end(), selection.begin(), ::tolower); int walletEnum = convertStringToEnum(selection, 1); if (walletEnum == (-1)) { std::cout << "Text entered did not match the available wallets, please try again." << std::endl; printPrompt(); continue; } else { return walletEnum; } } std::cout << "Error: Choosing wallet failed. Cash chosen as default. Please try again from the menu" << std::endl; return 0; }
void ConsoleSession::onCommand(const std::vector<std::string>& args) { if(args.empty()) { printPrompt(); return; } const std::string& commandName = args[0]; std::vector<std::string> commandArgs(args.begin() + 1, args.end()); const ConsoleCommands::Command* command = consoleCommands->getCommand(commandName); if(!command) { writef("Unknown command : %s\r\n", commandName.c_str()); } else { ConsoleCommands::Command::CallStatus status = command->call(this, commandArgs); switch(status) { case ConsoleCommands::Command::CS_Success: break; case ConsoleCommands::Command::CS_NotEnoughArgs: write("Not enough arguments\r\n"); break; case ConsoleCommands::Command::CS_TooMuchArgs: write("Too many arguments\r\n"); break; }; if(status != ConsoleCommands::Command::CS_Success) { writef("Usage:\r\n%s\r\n", command->usageExample.c_str()); } } printPrompt(); }
int chooseAttribute() { std::string selection; std::cout << "How would you like to label this transaction?" << "(Novelty,Food,Restaurant,Clothing,Gas,Bill,Vice,Home)" << std::endl; //printPrompt(); while (getline(std::cin, selection)) { if (std::cin.fail()) { std::cin.clear(); std::cout << "Incorrect input, please try again" << std::endl; printPrompt(); continue; } std::transform(selection.begin(), selection.end(), selection.begin(), ::tolower); int walletEnum = convertStringToEnum(selection, 2); if (walletEnum == (-1)) { std::cout << "Text entered did not match the available attributes, please try again." << std::endl; printPrompt(); continue; } else { return walletEnum; } } std::cout << "Error: Choosing attribute failed. Novelty chosen as default. Please try again from the menu." << std::endl; return 0; }
int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: test (folder you want to cd into) (folder you want to create)\n"); return -1; } //Test if external command can execute struct command_t extCommand; extCommand.name = "cd"; extCommand.argv[1] = "./"; printf("isExternalCommand: %d\n", isExternalCommand(&extCommand)); extCommand.name = "pwd"; printf("isExternalCommand: %d\n", isExternalCommand(&extCommand)); extCommand.name = "echo"; extCommand.argv[1] = "Hello World"; printf("isExternalCommand: %d\n", isExternalCommand(&extCommand)); extCommand.name = "mkdir"; extCommand.argv[1] = "temp"; printf("isExternalCommand: %d\n", isExternalCommand(&extCommand)); //Testing echo echoString("$PATH"); //Testing printWorkingDirectory printWorkingDirectory(); //Prompt should be set up properly printPrompt(); //Test changing directory changeDirectory(argv[1]); //Testing printWorkingDirectory printWorkingDirectory(); //Check that prompt updated its directory portion printPrompt(); //To check if mkdir makes a directory in the new working directory int ret; char *cmd[] = { "mkdir", argv[2], (char *)0 }; ret = execv("/bin/mkdir", cmd); return 0; }
int ckpmon_run(char *arg) { extern lua_State *L; gchar *pmon_input = NULL; char *pmon_buf = NULL; gsize length = 0; GRegex *regex; GMatchInfo *match_info; GError *err = NULL; printPrompt("PMON版本输入格式如下例:\"1.3.6\"\n请输入\n"); // get pmon spec version: pmon_input int len = getTableNumElement(L, "con", "PMONVER_LEN"); pmon_input = getNCharsPrompt("PMON版本条码", len, TRUE); if (pmon_input == NULL) { printPrompt("未输入\n"); return 1; } printPrompt("输入版本号为:"); printMsg(pmon_input); printMsg("\n"); // get pmon env version: pmon_env g_file_get_contents ("/proc/cmdline", &pmon_buf, &length, NULL); regex = g_regex_new (PMON_STR, G_REGEX_NO_AUTO_CAPTURE | G_REGEX_OPTIMIZE | G_REGEX_DUPNAMES, 0, &err); g_regex_match (regex, pmon_buf, 0, &match_info); gchar *pmon_named = g_match_info_fetch_named(match_info, "pmonver"); g_print ("%s\n", pmon_named); // cmp gchar *text_pmon_env = g_strdup_printf("本机的版本号[cmdline]为:%s\n", pmon_named); printPrompt(g_string_chunk_insert_const(text_chunk, text_pmon_env)); g_free(text_pmon_env); if (strcasecmp(pmon_input, (const char *)pmon_named)) { printNG("机器当前PMON版本号与标准不相符!\n"); return 1; } else { printOK("PMON版本号相符。\n"); } g_free(pmon_input); // TODO: here free g_strdup, but have not test g_free (pmon_named); g_match_info_free (match_info); g_regex_unref (regex); return 0; }
int main( void ) { MsgNode *list = NULL; MsgNode *node; char command[MAX_LINE]; char c; printPrompt(); // enter a loop, reading and executing commands from the user while( fgets(command,MAX_LINE,stdin) != NULL ) { char *p; // replace newline with end-of-string character if(( p = strchr(command,'\n')) != NULL ) { *p = '\0'; } p = command; while( isspace(*p)) { // skip any initial spaces p++; } c = *p; if( isdigit(c)) { // INSERT CODE FOR JUMPING TO MESSAGE k } else switch( c ) { case 'a': case 'A': // Add item // MODIFY THIS CODE, AS APPROPRIATE node = getNode(); printFull( node ); break; // INSERT CODE HERE // TO IMPLEMENT OTHER COMMANDS case 'h': case 'H': // Help printHelp(); break; case 'q': case 'Q': // Quit freeList( list ); printf("Bye!\n"); return 0; break; } printPrompt(); } return 0; }
int main(int argc, char **argv) { char currdir[DIRECTORY_LEN_MAX]; char homedir[DIRECTORY_LEN_MAX]; char **commands = NULL; unsigned int cmdCount = 0; /* Current directory is home directory */ if (getcwd(homedir, DIRECTORY_LEN_MAX) == NULL) perror("getcwd() error"); HOME = homedir; CMDCOUNT = &cmdCount; EXECPATH = argv[0]; /* Signal handlers */ signal(SIGINT, signalCallbackHandler); signal(SIGTSTP, signalCallbackHandler); while (1) { /* Update current working directory */ if (getcwd(currdir, DIRECTORY_LEN_MAX) == NULL) perror("getcwd() error"); /* Clean all zombie processes */ cleanZombies(); /* Print the prompt */ printPrompt(currdir); /* Do the Dew! */ commands = processCommand(commands, &cmdCount); } stringListFree(commands); return 0; }
/* * Return the cursor position of the cursor in the line. * Note 1: This function doesn't return the cursor position in the whole command line. * A line is every wide characters separated by L'\n' or L'\0'. * Note 2 : This function return the number of column used. * It may not correspond to the number of characters. */ static int sizeOfOneLineInTerm(wchar_t * CommandLine, unsigned int cursorLocation) { unsigned int beginningOfLine = cursorLocation; int sizeOfLineInTerm = 0; wchar_t saveLastWChar = 0; /* Character under cursor saved */ saveLastWChar = CommandLine[cursorLocation]; /* Set the end of the line to the cursor position */ CommandLine[cursorLocation] = L'\0'; /* Looking for the beginning of the line (L'\n' or beginning of the command line) */ while (CommandLine[beginningOfLine] != L'\n' && beginningOfLine) { beginningOfLine--; } /* If the line is the first of the command, prompt size must be added */ if (!beginningOfLine) { sizeOfLineInTerm += printPrompt(NOWRITE_PROMPT); } /* If L'\n' is found, the line start to the next character */ if (CommandLine[beginningOfLine] == L'\n') { beginningOfLine++; } /* Set the beginning of the line */ CommandLine += beginningOfLine; /* Get the number of column used by the line */ sizeOfLineInTerm += wcswidth(CommandLine, wcslen(CommandLine)); /* Previously saved character put back in the command line */ CommandLine[cursorLocation - beginningOfLine] = saveLastWChar; return sizeOfLineInTerm; }
EventChain<SocketSession> ConsoleSession::onConnected() { writef("%s - Administration console - Type \"help\" for a list of available commands\r\n", GlobalCoreConfig::get()->app.appName.get().c_str()); printPrompt(); return TelnetSession::onConnected(); }
char* readin ( FILE* in ){ char *cursor; int count; char* cmd = calloc(MAX_INPUT, sizeof(char)); cursor = cmd; char readin[5]; for (count = 0; count < MAX_INPUT; count++){ read(STDIN_FILENO, readin, 1); if(*readin == '\n') break; if(*readin == 127){ write(1, "\e[2K",4); for (int i = 0; i < count + prompt_len+1; i++){ write(1, "\b",1); } cursor--; *cursor='\0'; printPrompt(); write(1,cmd,count); continue; } if(*readin == '\033'){ read(STDIN_FILENO, readin, 1); //bracket (overwrote ansi escape) read(STDIN_FILENO, readin, 1); //LETTER (overwrote bracket) switch(*readin){ case 'A': if(hcurrent!=NULL){ ERASE_LINE; char* this = hcurrent->data; hcurrent=hcurrent->next; int len = strlen(this); write(1,this,len); cmd = this; cursor = cmd+len-1; } break; case 'B': if( hcurrent!=NULL){ ERASE_LINE; char* this2 = hcurrent->data; hcurrent=hcurrent->prev; int len2 = strlen(this2); write(1,this2,len2); cmd = this2; cursor = cmd+len2-1; } break; }
void ArxDbgEdInputContextReactor::beginDragSequence(const char* promptString) { m_dragJustStarted = true; printReactorMessage(_T("Begin Drag Sequence")); if (m_showDetails) printPrompt(promptString); }
void ArxDbgEdInputContextReactor::beginGetString(const char* promptString, int initGetFlags) { printReactorMessage(_T("Begin Get String")); if (printDetails()) { printPrompt(promptString); printInitGetFlags(initGetFlags); } }
int main(int argc, char **argv){ setup(); //initialize everything printWelcome(); printPrompt(); //first prompt while(CONT == 1){ //Continue running the shell if CONT is not set to 0 by something; if(getInput() == 1){ //Some input strings will make the process start over. continue; } processInput(); if(CONT == 0){ //In case something has set CONT to 0, don't print the prompt again. break; } printPrompt(); } return 0; }
/* processMoves(void) reads movement commands, processing each command, in turn to move the corresponding car within the carpark. Each movement command is constrained to ensure the corresponding car does not collide with any other car and that the car remains within the bounds of the carpark. A movement command is performed (and the carpark updated to reflect the movement) if the corresponding car can move in the given direction. At the completion of each movement command (regardless of whether the command lead to actual movement), the current state of the carpark is printed. The function completes immediately if a movement command leads to the target car exiting. The function terminates the program if any command is invalid. */ static void processMoves(void) { char line[BUFSIZ]; char car; char direction; int amount; DIRECTION d; int i = 0; while(!hasExited()) // make sure the TARGETCAR is not at the exit location { printPrompt(); // prompt the user for a move fgets(line, sizeof line, stdin); trimLine(line); sscanf(line, "%c %c %d", &car, &direction, &amount); // assign the users move to appropiate variables if(!isValidCarparkEntry(car)) // check the car is defined in the carpark { fprintf(stderr, "Fatal Error: car %c was not found in the grid\n", car); exit(EXIT_FAILURE); } /* The following code sets the enum value from the user input */ if(direction == 'N' || direction == 'n') { d = NORTH; } else if(direction == 'S' || direction == 's') { d = SOUTH; } else if(direction == 'E' || direction == 'e') { d = EAST; } else if(direction == 'W' || direction == 'w') { d = WEST; } moveCar(car, d, amount); i = moveCar(car, d, amount); printf("Processed move: %c %c %d\n", car, direction, amount); printCarpark(); } printf("The target car is now free after %d moves!\n", i); }
int main(int argc, char *argv[]){ sleepy = argc != 1? 0 : 1;//So that if a machine is playing, sleeps can be removed struct timespec delayTime;// delayTime.tv_sec = 0;//These three lines create something that nanosleep can use to sleep. Details can be changed to change sleep time delayTime.tv_nsec = 500*1000*1000;//Starting at 500,000,000 nanoseconds (0.5s). Can be reassigned. puts("This is an in-development version. The treasure and traps are always visible."); char dungeon[DUNGEON_X][DUNGEON_Y]; uint8_t playerPos[2] = {1, 1};//Starting position for the player uint8_t playing = 1; //So we don't instantly exit uint8_t monsterPos[2] = {2, 2}; //Starting monster position - randomisation incoming uint8_t awake = 0; //The monster starts invisible. This doubles as 'is the monster active?' uint8_t trapPos[2][2] = {{1, 2}, {3, 5}}; //Two traps to wake the monster - will be randomised uint8_t treasurePos[2] = {2, 1}; //The treasure was once in the same place as the monster. Randomisation will need to ensure that this is never the case setUpDungeon(&dungeon, playerPos, trapPos, monsterPos, treasurePos);//Because setUpDungeon takes a pointer, and a bunch of positions to tell it where stuff goes //validateDungeon(&dungeon);//As does validateDungeon. Commented because reasons if (sleepy) nanosleep(&delayTime, NULL);//Wait a moment while(playing){//If you're not playing anymore, the game really ought to end system("clear");//We are now officially *NIX specific uint8_t isValidCommand = 0;//So that if the input is invalid, it can be ignored and retried without redrawing uint8_t ignoreNext = 0;//For invalid strings, helps prevent ignorance of next valid input int8_t parseReturn; setUpDungeon(&dungeon, playerPos, trapPos, monsterPos, treasurePos);//Because setUpDungeon takes a pointer to a char[][] //and a bunch of positions so that all things are in their rightful places drawDungeon(&dungeon, playerPos, trapPos, monsterPos, awake, treasurePos);//drawDungeon must know all things' positions printPrompt(&dungeon, awake, playerPos, trapPos, monsterPos, treasurePos); char text[3];//Command char, \n and \0 while(!isValidCommand){ fgets(text, 3, stdin);//Technically, this reads a file. stdin is a file, though. Uses a pointer, the number of characters you want and file if((text[1] == '\n' && text[2] == '\0') || text[1] == '\0'){//If the only input characters are the command, \n and EOF, or the command is \nEOF //in the event that the previous command was invalid and of the correct length type. //Rejects strings terminated with ^D but no \n, and glitches out, but that's not the kind of thing if(ignoreNext || text[0] == '\n'){ //any normal person would be inputting, anyway. Machines will learn what constitutes valid, too ignoreNext = 0; } else{ parseReturn = parseUserInput(&dungeon, text[0], &playerPos, &awake, &trapPos); isValidCommand = parseReturn == 1? 1 : 0; } } else{ if(!ignoreNext){ puts("Invalid command."); ignoreNext = 1; if (sleepy) nanosleep(&delayTime, NULL); } } } if (sleepy) nanosleep(&delayTime, NULL); doMonsterMove(&dungeon, playerPos, &monsterPos, &playing); } return 0; }
int keyboard_run(char *arg) { printPrompt("进入键盘测试。\n"); gdk_threads_enter(); draw_kbd(); gdk_threads_leave(); if (kbd_result) { printNG("键盘测试失败\n"); } else { printOK("键盘测试通过\n"); } return kbd_result; }
std::string chooseDescription() { std::string selection; std::cout << "What is the transaction description?" << std::endl; printPrompt(); while (getline(std::cin, selection)) { if (std::cin.fail()) { std::cin.clear(); std::cout << "Input failed, please try again." << std::endl; printPrompt(); continue; } if (!(std::all_of(selection.begin(), selection.end(), ::isalpha))) { std::cout << "Profile name can only contain alphabetic characters!" << std::endl; printPrompt(); continue; } else return selection; } std::cout << "Error: Defaulted to 'null'. Please try again from the menu" << std::endl; return "null"; }
void ArxDbgEdInputContextReactor::beginEntsel(const char* promptString, int initGetFlags, const char* pKeywords) { printReactorMessage(_T("Begin Entsel")); if (printDetails()) { printPrompt(promptString); printInitGetFlags(initGetFlags); printKeywords(pKeywords); } }
int main( int argc , char** argv , char** envp ){ //initHerstory(); int opt; /* Check for file */ if(argv[1] != NULL && argv[1][0] != '-'){ /* first argument exists and isnt a flag */ command* c = calloc(1, sizeof(command)); c->argv[1] = argv[1]; sh( c ); exit(0); } while ((opt = getopt(argc, argv, "d")) != -1) { switch (opt) { case 'd': debug = TRUE; fprintf(stderr, "%s\n", "<Entering debugging mode>"); break; default: /* '?' */ fprintf(stderr, "Usage: %s [-d] (debugging)\n",argv[0]); exit(EXIT_FAILURE); } } int running = TRUE; char* input = calloc(MAX_INPUT, sizeof(char)); process* pro; while(running){ printPrompt(); input = readin(stdin); if(input[0] != '\0'){ pro = parse_cmd(input); ///addToHistory(pro->original); running = runProcess(pro); } } command* cur = pro->head; while(cur != NULL){ command* next = cur->next; free(cur); cur = next; } free(pro); return 0; }
float chooseAmount() { std::string selection; std::cout << "What amount would you like to enter?" << std::endl; printPrompt(); while (getline(std::cin, selection)) { if (std::cin.fail()) { std::cin.clear(); std::cout << "Input failed, please try again." << std::endl; printPrompt(); continue; } if (!(std::all_of(selection.begin(), selection.end(), ::isFloat))) { std::cout << "Input contained non-numeric characters. Please try again." << std::endl; printPrompt(); continue; } else return std::stof(selection); } std::cout << "Error: Defaulted to 0. Please try again from the menu" << std::endl; return 0; }
int chooseID() { std::string selection; std::cout << "Enter a transaction ID" << std::endl; printPrompt(); while (getline(std::cin, selection)) { if (std::cin.fail()) { std::cin.clear(); std::cout << "Input error. Please try again." << std::endl; printPrompt(); continue; } if (!(std::all_of(selection.begin(), selection.end(), ::isdigit))) { std::cout << "ID entered contains non-numeric characters. Please try again" << std::endl; printPrompt(); continue; } else return std::stoi(selection); } std::cout << "Error: Please try again from menu" << std::endl; return (-1); }
int main(int argc, char* argv[]) { char buf[MaxCommandLine]; int n, paramNumber; int commandType; char* params[4]; printPrompt(); while ((n=read(STDIN_FILENO, buf, MaxCommandLine))>0) { buf[n]='\0'; commandType=parseCommand(buf, params, ¶mNumber); if (commandType==-1) { printf("illegal command\n%s"); } else { commandArray[commandType](params, paramNumber); } printPrompt(); } return 0; }
void ArxDbgEdInputContextReactor::beginGetColor(const int* dfault, const char* promptString, int initGetFlags, const char* pKeywords) { printReactorMessage(_T("Begin Get Color")); if (printDetails()) { printDefaultInt(dfault); printPrompt(promptString); printInitGetFlags(initGetFlags); printKeywords(pKeywords); } }
void ArxDbgEdInputContextReactor::beginGetScaleFactor(const AcGePoint3d* pointIn, const char* promptString, int initGetFlags, const char* pKeywords) { printReactorMessage(_T("Begin Get Scale Factor")); if (printDetails()) { printPointIn(pointIn); printPrompt(promptString); printInitGetFlags(initGetFlags); printKeywords(pKeywords); } }
void ArxDbgEdInputContextReactor::beginGetCorner(const AcGePoint3d* firstCorner, const char* promptString, int initGetFlags, const char* pKeywords) { printReactorMessage(_T("Begin Get Corner")); if (printDetails()) { printFirstCorner(firstCorner); printPrompt(promptString); printInitGetFlags(initGetFlags); printKeywords(pKeywords); } }
int webcam_run(char *arg) { printPrompt("进入摄像头测试\n请确认开启摄像头(Fn + F10)\n并根据实际情况选择'OK'或者'NG'\n"); gdk_threads_enter(); camera_work(); gdk_threads_leave(); if (cam_result) { printNG("摄像头测试失败\n"); } else { printOK("摄像头测试成功\n"); } return cam_result; }
void ArxDbgEdInputContextReactor::beginNentsel(const char* promptString, Adesk::Boolean pickFlag, int initGetFlags, const char* pKeywords) { printReactorMessage(_T("Begin Nentsel")); if (printDetails()) { CString str; printPrompt(promptString); printValue(_T("PICK FLAG"), ArxDbgUtils::booleanToStr(pickFlag, str)); printInitGetFlags(initGetFlags); printKeywords(pKeywords); } }
void debugconsole_init() { int read_offset = 0; int read; default_console->info.handle_backspace = 0; while (1) { printPrompt(); read_offset = 0; while (read_offset < 255) { read = console_read(NULL, currentLine + read_offset, 1); if (currentLine[read_offset] == 0x8 || currentLine[read_offset] == 0x7f) { if (read_offset == 0) continue; currentLine[read_offset--] = 0; currentLine[read_offset] = 0; console_write2(NULL, "\x08"); continue; } if (currentLine[read_offset] == '\n' || currentLine[read_offset] == '\r') { currentLine[read_offset] = '\0'; break; } read_offset += read; } char *strtok; char *command = kmalloc(sizeof(char) * 255); char *arg = kmalloc(sizeof(char) * 32); char **argv = kmalloc(sizeof(char*) * 32); uint8_t argc = 0; command = strtok_r(currentLine, " ", &strtok); while ((arg = strtok_r(NULL, " ", &strtok))) { argv[argc++] = arg; } executeCommand(command, argc, argv); } }
int main(int argc, char*argv[]) { // Code which sets stdout to be unbuffered // This is necessary for testing; do not change these lines USE(argc); USE(argv); setvbuf(stdout, NULL, _IONBF, 0); // Main loop that reads a command and executes it while (1) { // You should issue the prompt here printPrompt(); // You should read in the command and execute it here readCommand(); } return 0; }
/* * main * * arguments: * int argc: the number of arguments provided on the command line * char *argv[]: array of strings provided on the command line * * returns: int: 0 = OK, else error * * This sets up signal handling and implements the main loop of tsh. */ int main(int argc, char *argv[]) { /* Initialize command buffer */ char* cmdLine = malloc(sizeof(char*) * BUFSIZE); /* shell initialization */ if (signal(SIGINT, sig) == SIG_ERR) PrintPError("SIGINT"); if (signal(SIGTSTP, sig) == SIG_ERR) PrintPError("SIGTSTP"); /* Terminated or stopped child */ while (!forceExit) /* repeat forever */ { /*Insert tsh$ prompt*/ printPrompt(); /* read command line */ getCommandLine(&cmdLine, BUFSIZE); if (strcmp(cmdLine, "exit") == 0) forceExit = TRUE; /* checks the status of background jobs */ if(!forceExit){ CheckJobs(); fflush(NULL); } /* interpret command and line * includes executing of commands */ Interpret(cmdLine); fflush(NULL); //getPath(); } /* shell termination */ free(cmdLine); return 0; } /* main */