luistripa luistripa - 3 months ago 17
C Question

Compare a variable and a string

I am trying to code a C program to start specific functions on the OS X El Capitan.
The code looks like this:

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

int main()
{
char mainchoice;
printf(">>> ");
scanf("%s", &mainchoice);
if (strcmp(&mainchoice, "start ftp") == 0) {
system("ftp");

}
else if (strcmp(&mainchoice, "start say") == 0) {
system("say hello");
}
else {
system("say Error")
}

}


This is just a sample code.

When I run it, it always says error via the say command. What am I doing wrong?

Answer

Focus here:-

char mainchoice; //declared as a char

scanf("%s", &mainchoice); //using the %s placeholder which is for string

//for character it is %c

Getting the logic behind your code is you want to enter a String not a character.

Make an array of characters like this:-

char mainchoice[20]; //this can hold your string, one character at one index each of the array

Since, your are using multi word in string comparison("start say")

(strcmp(&mainchoice, "start say") == 0)

scanf does not work for multi words. scanf stops reading from the keyboard as soon as you provide a whitespace, tabs, newline.

For solving that problem, use fgets. It's the best way to read multi words or even whole sentences. Never use gets()! It is vulnerable to buffer overflow!

fgets(mainchoice, 20, stdin);