-3
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
    char string;
    printf("Hello\n");
    printf("What would you like to do\n");
    printf("Here are the options\n");
    printf("s : How are you\n");
    printf("c : What would you like to search\n");
    scanf("%s",&string);
    if(string == 'h')
        printf("iam fine\n");

    else if (string == 's')
        printf("What would you like to search\n");
    scanf("%s",&string);
    system(string);
    return 0;
}

When I run this after it says what would you like to search and I type run notepad it stops working.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

1

Problem 1. defining string as char won't work for you. you need an array.

define char string[100] = {0};

Problem 2. scanf("%s",&string); not required, can be used as scanf("%s",string);

problem 3. if(string == 'h'), wrong. array contents cannot be compared using == operator. you've to use strcmp() function.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

There are two problems with this scanf:

printf("What would you like to search\n");
scanf("%s",&string);
system(string);
  1. string is a single char - the scanf will result in a buffer overrun.

  2. The %s format specifier only reads until the next whitespace.

To fix the problem you should allocate a larger buffer and read an entire line:

char buffer[1024];
printf("What would you like to search\n");
fgets(buffer, sizeof buffer, stdin);
system(buffer);
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82