4

I tried to write program that scan a string from user and check it what the user input and if it is true do somthing and if it's not do somthing else. the code i wrote is like this:

#include<stdio.h>
#include<conio.h>

int main()
{
    char string[20];
    printf("Enter a sentence : ");
    scanf("%s",&string);
    if(strcmp(string,"what's up")==0)
        printf("\nNothing special.");
    else
        printf("\nYou didn't enter correct sentence.");
    getch();
    return 0;
}

but it doesn't work correct.I think because the program can't recognize the space when it want to scan.What should i do?(I'm new to c,so please explain what did you do.)

amin
  • 51
  • 4

3 Answers3

3

%s format specifier can't be used to scan a string with space.

You need to use fgets()

size_t n;
fgets(string,sizeof(string),stdin);
n = strlen(string);
if(n>0 && string[n-1] == '\n')
string[n-1] = '\0';

PS: fgets() comes with a newline character.So you need to gently remove it as shown above

Gopi
  • 19,784
  • 4
  • 24
  • 36
2

you can still use scanf but like this :

#include<stdio.h>
#include<conio.h>

int main()
{
    char string[20];
    printf("Enter a sentence : ");
    scanf(" %[^\n]s",string);
    if(strcmp(string,"what's up")==0)
        printf("\nNothing special.");
    else
        printf("\nYou didn't enter correct sentence.");
    getch();
    return 0;
}

To prevent buffer overflow,you can write scanf(" %19[^\n]s",string);

machine_1
  • 4,266
  • 2
  • 21
  • 42
0

you can use the getline1() function to get the entire line as shown below:

 /* getline1: read a line into s, return length*/
    int getline1(char s[],int lim)
    {
    int c, i;
    for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
    s[i] = c;
    if (c == '\n') {
    s[i] = c;
    ++i;
    }
    s[i] = '\0';
    return i;
    }

lim specifies the maximum length of the line.

Jay Dabhi
  • 58
  • 6