首页 > 解决方案 > 在while循环中使用scanf读取带有空格的用户输入?

问题描述

我正在处理一些代码,我试图在以下命令中读取这些代码,这将导致我的程序中的某些函数被调用:

PRINT
INSERT 0,Folders,Folders for storing related papers,25
PRINT
QUIT

我一直在尝试不同的方式来读取这个输入,它来自./inventory test02/inventory02-actual.txt < test02/input02.txt > test02/actual02.txt,其中上面显示的这些命令位于文件 input-02.txt 中。

我主要一直在使用scanf,但也尝试过fgets,但我在我想要的方面取得了最大的成功scanf。我最初尝试过scanf("%s", command),在这种情况下, scanf 不接受空格,因此程序终止。

//Keep re-prompting user for commands until you reach EOF{
  while ((scanf("%[0-9a-zA-Z, ]s", command) == 1)) {  
    printf("====================\nCommand? ");
    printf("%s\n", command);      
    if (strcmp(command, "PRINT") == 0) {     
      print(list);    
    } else if (strcmp(substring(command, START, INSERT_END), "INSERT") == 0) {    
      //Get the substring - this is the input after "INSERT"
      char string[MAX_LEN_COMMAND];
      strcpy(string, substring(command, OFFSET, strlen(command)));                     
      insert(string, list);   
    } else if (strcmp(command, "PRINTREVERSE") == 0) {
      printReverse(list);
    } else {
      printf("Invalid command passed.\n"); 
      exit(EXIT_BAD_INPUT);
    }
  }

目前,当我运行我的代码时,只读入第一个命令“PRINT”。似乎我无法从 input-02.txt 读取下一行输入。有没有办法可以正确读取这些命令?此外,在我的程序读入“INSERT”之后,它会读入“0,文件夹,用于存储相关文件的文件夹,25”作为命令,这是不应该的。它应该直接转到下一个命令,即“PRINT”。我在调用该insert方法后尝试使用 continue 语句,但这不起作用。有没有人有什么建议?

编辑:使用 fgets 更新代码。

与其发布我在上面调用的所有函数,我认为传递 aprintf来向我们展示命令是什么对于一个可重现的示例来说可能足够简单!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define OFFSET 7
#define START 0
#define INSERT_END 5

static const char *substring(char command[], int start, int end);

int main(int argc, char **argv) 
{
  //Get user input for commands    
  char command[500];

  //Keep re-prompting user for commands until you reach EOF{
  while (fgets(command, sizeof(command), stdin) != NULL) {  
    printf("====================\nCommand? ");
    printf("%s\n", command);      
    if (strcmp(command, "PRINT") == 0) {     
      printf("%s", command);    
    } else if (strcmp(substring(command, START, INSERT_END), "INSERT") == 0) {    
      printf("%s", command);   
    } else if (strcmp(command, "PRINTREVERSE") == 0) {
      printf("%s", command);
    } else {
      printf("Invalid command passed.\n"); 
      exit(1);
    }
  }
}

static const char *substring(char command[], int start, int end) 
{
  int i = 0;
  int j = 0;
  char *sub;
  sub = (char *)malloc(500 * sizeof(char));
  for (i = start, j = 0; i <= end; i++, j++) {
    sub[j] += command[i];
  }
  sub[j] = '\0';
  return sub;
}

我得到的输出是:

====================
Command? PRINT

Invalid command passed.

标签: cstringfileioscanf

解决方案


由于您正在阅读一行,因此您将获得更好的成功fgets

char command[101];   

while (fgets(command, 100, stdin))
{
// rest of the code can be the same
}

推荐阅读