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?
sizeof charis always 1 so you don't need to be so explicit.\n