Get and check strings in c language

I tried to write a program that scans a string from a user and checks it, what the user enters, and if it is true, does something, and if it does nothing. The code I wrote looks like this:

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

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

but it does not work correctly. I think because the program cannot recognize the space when it wants to scan. What should I do? (I am new to c, so please explain what you did.)

+4
source share
3 answers

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 up")==0)
        printf("\nNothing special.");
    else
        printf("\nYou didn't enter correct sentence.");
    getch();
    return 0;
}

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

+2
source

%s .

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

+3

you can use the getline1 () function to get the whole 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 indicates the maximum length of the string.

0
source

Source: https://habr.com/ru/post/1611742/


All Articles