我正在编写交互式数独游戏并从控制台解析命令。
我想将用户命令限制为最多256个字符,而任何多余的char都会打印一条错误消息,并通知他它超过了最大长度。
因此,我为256个长度的char数组分配了内存,并通过fgets函数读取了此输入,然后将其传递给解析器函数,这是我这部分的代码-注意输入是我从fgets函数传递的输入。
Command parseCommand(char *input, int upperBound, MODE* mode){
Command command;
char* token;
char *copyInput = (char*) malloc(strlen(input)*sizeof(char));
if(copyInput == NULL){
printf("Error: parseCommand has failed\n");
free(copyInput);
exit(EXIT_FAILURE);
}
command.cmd = ERROR;
strcpy(copyInput,input);
token = strtok(input,delim);
if(strlen(copyInput) > 256){
command.cmd = MAX_ARGS_REACHED;
clear();
}...//More code following to that but irrelvant
现在,我相信问题出在我清楚的功能上,因为那里什么都没有发生,而且永远不会离开它,但是如果我按Enter twich,那么它是258个字符,它可以完美地工作,例如,每一个大于257的大小的输入都可以完美地工作,仅257问题。
void clear(){
int c = 0;
while ((c = getchar()) != '\n' && c != EOF) { }
}
希望在这里获得帮助!
edit-这是显示我如何读取输入并将其传递给上面的函数的代码-
void runGame(){
Game* game;
char* input = (char*) malloc(256 * sizeof(char));
if(input == NULL){
printf("Error: Program has failed!\n");
free(input);
exit(EXIT_FAILURE);
}
printf("Welcome to Sudoku Game!\n");
game = createGame();
while(1){
Command command;
printf("Please enter a Command\n");
if(!fgets(input,ARRSIZE,stdin)){/*checks if reading user input failed or EOF*/
exitCommand(game);
free(input);
return;
}
command = parseCommand(input,game->rows,&game->mode);//More code following to that
至少这个问题
内存分配不足
需要null字符 +1。 (C中不需要铸造)
// char *copyInput = (char*) malloc(strlen(input)*sizeof(char));
char *copyInput = malloc(strlen(input) + 1);
strcpy(copyInput,input);
获得输入后,请检查是否存在换行符。如果不是,请清除挂起的字符。
while ( 1) {
Command command;
printf("Please enter a Command\n");
if ( fgets ( input, ARRSIZE, stdin)) {/*checks if reading user input failed or EOF*/
if ( ! strchr ( input, '\n')) {//no newline. clear pending characters.
clear ( );
}
}
else {
exitCommand(game);
free(input);
return;
}
}