0

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");
    }
}
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
Haxk20
  • 77
  • 7

2 Answers2

2

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]

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Thanks man this works. How i see i must continue to learn C better. – Haxk20 Dec 13 '15 at 18:28
  • And i have i more question how the fgets() works and what parameters i must use for it or is it the same as scanf() ? – Haxk20 Dec 13 '15 at 18:31
  • `fgets()` reads until it hits a `\n` or `EOF`. E.g. usage: `char buf[256]; fgets(buf, sizeof buf, stdin);`. Note that `fgets()` would also read the `\n` if there's space in the buffer. So if you want to trim the newline, do: `char *p = strchr(p, '\n'); if(p) *p = 0;` after the call to `fgets()`. – P.P Dec 13 '15 at 18:33
  • Ok and do you have any good tutorial for C because i now only basics . – Haxk20 Dec 13 '15 at 18:35
  • You can read [The Definitive C Book Guide and List](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) for the recommendations. And you'll also find the [C-FAQs](http://c-faq.com/) pretty useful. – P.P Dec 13 '15 at 18:36
0

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");
}
mbass
  • 34
  • 3