Haxk20
Haxk20

Reputation: 77

Char and if stament in C

I have a problem to compare the char and "some text" inside if clause. There is the code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char *start[99];
    printf("Welcome to MyOS 1");
    printf("\n" "#: ");
    scanf("%[98]", &start);
    if (&start == "help")
    {
        printf("All commands:" "File" "Calculator");
    }
}

Upvotes: 0

Views: 131

Answers (2)

mbass
mbass

Reputation: 34

There are several issues with your code. You probably want an array of char, char start[99]. You should use strcmp or strncmp to compare strings. Just making your code work could be done like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
{
    char start[99];
    printf("Welcome to MyOS 1");
    printf("\n" "#: ");
    fgets(start, sizeof(start), stdin);
    if (isalpha((unsigned char) *start) != 0)
    {
        if (strncmp(start, "help", 4) == 0)
            printf("All commands: File Calculator\n");
        else
            printf("No such command.\n");
    }
    else
        fprintf(stderr, "Error\n");
}

Upvotes: 0

P.P
P.P

Reputation: 121347

start is an array of pointers to char and you probably want an array of char. So change

char *start[99];

to

char start[99];

and change scanf("%[98]", &start); to scanf("%[98]", start);

And to compare c-strings, use strcmp(). So change

 if (&start == "help")

to

 if ( strcmp(start, "help") == 0 )

If you want to read a line, use fgets() instead of scanf().

Enabling compiler warnings would help too. For your code, GCC issues:

warning: format ‘%[98’ expects argument of type ‘char *’, but argument 2 has type ‘char * (*)[99]’ [-Wformat=]

warning: comparison of distinct pointer types lacks a cast

warning: comparison with string literal results in unspecified behavior [-Waddress]

Upvotes: 2

Related Questions