String comparison inside if condition is malfunction

I tried to program in C but was not successful. I have simple source code and need to match multiple letters in if (char)

. It displays the following error message (in linux terminal using gcc):

main.c: In function `main ': main.c: 16: 23: warning: character constant too long for its type [enabled by default]

if (firstName [20] == 'Vojta') {

Source:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    /* code */
    char firstName[20];
    char lastName[40];
    char password[20];
    char confpasswd[20];
    int age;

    printf("Please write your first and last name:");
    scanf("%s%s", firstName, lastName);
    printf("%s %s:\n", firstName, lastName);

    if (firstName[20] == 'Vojta'){
        printf("\ncool\n");
    }

    return 0;
}

      

+3


source to share


2 answers


Point 1

Use strcmp()

for string comparison.

Point 2

Edit

scanf("%s%s", firstName, lastName);

      



to

scanf("%19s %39s", firstName, lastName);

      

and do check the return value scanf()

to ensure success. However, it is better if you use two scanf()

separately to take two inputs which will be less error prone.

Also, as a suggestion, you can read fgets()

and strtok()

for how to read the whole line as input and denote the part you want .

+10


source


With respect to this line:

if (firstName[20] == 'Vojta'){

      

firstName

is an array and its value was set via scanf()

. Therefore, the first name will contain a terminating NULL char ( '\0'

). Therefore, the contents firstName

, if the user entered 'Vojta'

will be 'V'

, 'o'

, 'j'

, 't'

, 'a'

, '\0'

, and then 14 garbage characters.

Due to the finite '\0'

(which has been inserted scanf()

) the contents of firstName

a valid row.

The best way to compare content firstName

to some string literal is to compare it to a string literal using a function strcmp()

.

Note: the current code is comparing position (offset) 20 in firstName

(which is out of bounds of the array and hence results in undefined behavior).

Here's an example of the correct way to compare strings:



if( 0 == strcmp( firstName, "Vojta" ) )

      

Note the double quotes ( "

) around the string literal.

These double quotes make it a string literal, not just a bunch of characters that the compiler will evaluate as an "int" value.

Note: The individual characters can be represented using single quotes around each character, as in: 'V'

, 'o'

, 'j'

, 't'

, 'a'

.

Function strcmp()

  • returns < 0

    if the first parameter (content firstName

    ) precedes (in alphabetical order) the second parameter.
  • returns > 0

    if the first parameter (content firstName

    ) appears after (in alphabetical order) the second parameter.
  • returns 0

    if the first parameter matches the second parameter.
+2


source







All Articles