0

This is my code (Note that I'm on linux) :

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

int main(){
    system("clear");
    char command[300];
start:
    printf("user@clo2>>");
    gets(command);
    if (strcmp(command,"exit")==0){
        system("clear");
        exit(1);
    }
    if (strcmp(command,"--version")==0){
        printf("CLO2 Version : 1.0");
        printf("\n");
        goto start;
    }

    return 0;
}

If the user enters a text that the program can't find then I want it to print the text "NOT FOUND".

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

2

Use else if to test each possibility, then use a final else for NOT FOUND.

Other improvements you should make:

  1. Use a loop rather than goto.
  2. Use fgets() rather than gets(), which has been removed from the language because it's unsafe.
  3. Since fgets() leaves the newline in the buffer, you should include that in the strings you compare with.
  4. Don't use exit(1) unless the program is exiting due to an error. Just break out of the loop.
  5. You need <string.h> to get the declaration of strcmp().
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(){
    system("clear");
    char command[300];
    while (1) {
        printf("user@clo2>>");
        fgets(command, sizeof command, stdin);
        if (strcmp(command,"exit\n")==0){
            system("clear");
            break;
        } else if (strcmp(command,"--version\n")==0){
            printf("CLO2 Version : 1.0");
            printf("\n");
        } else {
            printf("NOT FOUND\n");
        }
    }

    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • To check the value returned by *fgets* allows to manage the EOF case, your program will never end if the input is redirected on a file. The entered commands being on one word `scanf("%299s", command)` seems a better choice than *fgets*. To use *printf* to print a string as it is done or worst a single char is also expensive for nothing. `while (fputs("user@clo2>>", stdout), scanf("%299s", command) == 1) { if ... puts("CLO2 Version : 1.0"); } else { puts("NOT FOUND"); } ..` can be proposed in second choice – bruno Jan 09 '21 at 08:27
  • When I press enter then still says command not found. Is there any way I can prevent that from happening? – FineCoder2120 Jan 09 '21 at 14:16
  • Anything other than `exit` or `--version` will say NOT FOUND. If you want to treat an empty input differently, you need to check for that explicitly. Don't forget to include the newline. – Barmar Jan 09 '21 at 22:25