0

I am trying to implement a minishell where if the user wants to exit the programm he is asked if he really wants to exit.

int main(int argc, char * argv[]){

char cwd[256];
char input[256];
char *command;

while(1) {
    //return user-info and current working directory
    getcwd(cwd, sizeof(cwd));
    printf("%s@miniShell:%s$ ", getpwuid(getuid())->pw_name, cwd);

    fgets(input, 256, stdin);
    command = strchr(input, '\n');

    if(command){
        *command = '\0';
    }

    if(strncmp(input, "exit",4)==0){
        cout << "Do you want to quit (y/n) ?" << endl;

        string isExit = "";
        cin >> isExit;

        if(isExit == "y"){
            exit(0);
        }
        continue;
    } 
} 

return 0;
}

Exiting the programm works very well but if the user chooses to not to exit the shell it results in printing the working directory in the next line twice. What am I doing wrong and how can I fix this?

user3386109
  • 32,020
  • 7
  • 41
  • 62
rees
  • 1
  • Mixing `cin` and `fgets` may be the source of the problem. I suspect that `fgets` is reading a blank line because `cin` leaves the newline character in the input buffer. – user3386109 Apr 28 '21 at 19:50
  • Very related: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Ted Lyngmo Apr 28 '21 at 19:50

0 Answers0