0

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?

2
  • Your scanf call is prone to buffer overflows. Also, sizeof char is always 1 so you don't need to be so explicit. Commented Mar 8, 2014 at 9:40
  • in order to continue, you have to read that \n Commented Mar 8, 2014 at 9:41

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right. I tried to add a line "scanf("%s");" after "scanf("%[^\n]", command);" It works now
0
  1. You need to check the return value of scanf
  2. Be careful with buffer overflow
  3. Need to eat new lines

2 Comments

The return value of scanf is 0.
you need to check. not tell. "These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.