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.)

2
  • 1
    change scanf("%s",&string); to scanf("%19[^\n]", string); also you need #include <string.h> Commented Oct 15, 2015 at 9:22
  • 1
    scanf needs other formats to be able to read input containing white-space. Commented Oct 15, 2015 at 9:22

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.