質問

I am new in c and meet this strange problem: I want to write a c code to let user enter command and do some jobs, this is my code:

int main()
{
  const int size = 100;
  while(1){
    char* currentDir;
    if((currentDir = getcwd(currentDir, 1024)) == NULL) {
      fprintf(stderr, "getcwd failed.\n");
      exit(0);
    }
    printf("%s > ", currentDir);

    char *command;
    command = (char*)calloc(size, sizeof(char));
    scanf("%[^\n]", command);
    if(strcmp("exit", command) == 0) {
      printf("%s\n", command);
      exit(0);
    }
    else {
      //do jobs based on user input
    }
    free(command);
  }
}

If user enter "exit", the program will end. But if user enter other string like "ll" or something else, the program will keep looping and never let user to enter another command. Why?

役に立ちましたか?

解決

This line:

scanf("%[^\n]", command);

Is reading characters up to but not including a newline and putting them into command. The newline is left in the input buffer.

When you execute that statement the next time around the loop, it does the same thing ... except that the first character it will encounter will be the same newline that it saw last time. Net result: it sets command to an empty string, and leaves the newline for the next call. And so on.

You need to consume that newline.

他のヒント

  1. You need to check the return value of scanf
  2. Be careful with buffer overflow
  3. Need to eat new lines
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top