简体   繁体   中英

Comparing strings in C using strcmp

I am trying to learn to program in C but am having trouble with manipulating strings as C treats strings as arrays.

My aim was to make a program that stores the users first name and surname.

Here is my progress:

#include <stdio.h>

int main(int argc, const char * argv[]) {

//defining the variables
char first_name[100];
char surname[100];
char ch[2];


// Asking for the first name and storing it
printf("What's your first name?\n");
scanf("%s", first_name);

// Prints the first name
printf("Hey %s!\n",first_name);


//Asks the user if they want to store their surname
printf("Would you like to tell me your second name? This is optional so type 'Y' for yes and 'N' for no.\n");
scanf("%s", ch);

//validate if they want to store it or not
if (ch == "Y"){
    printf("What is your surname?\n");
    scanf("%s", surname);
    printf("Your whole name is %s %s", first_name, surname);
 }

return (0);
}

However, with this code, I get an error because my IDE(xCode) tells me to use the strcmp function. I then edited the code to become this:

    if (strcmp(ch, "Y")){
        printf("What is your surname?\n");
        scanf("%s", surname);
        printf("Your whole name is %s %s", first_name, surname);
    }

However variable ch is not a literal and so is not comparable.

Sidenote

I did try to compare two literals too, just to see how it works:

char *hello = "Hello";
char *Bye = "Bye";


if (strcmp(hello, Bye)){
    printf("What is your surname?\n");
    scanf("%s", surname);
    printf("Your whole name is %s %s", first_name, surname);
}

But even this gave an error:

Implicitly declaring library function 'strcmp' with type 'int (const *char, const *char)'

I believe I am not able to do this due to my lack of experience so it would be much appreciated if you could help me understand what I'm doing wrong and how I can fix the problem.

You need to include the appropriate header:

#include <string.h>

Also note that your desired logic probably calls for:

if (!strcmp(hello, Bye))

Instead of:

if (strcmp(hello, Bye))

Since strcmp returns 0 in case of equality.

There are two problems here. Firstly you need to see what value is returned by the strcmp and secondly you must use the approprate hedder.

You must use:

#include <string.h>

Secondly, you must edit your if-else statement so it is like this:

if (strcmp(ch, "Y") == 0){
    printf("What is your surname?\n");
    scanf("%s", surname);
    printf("Your whole name is %s %s", first_name, surname);
}

We do this because the strcmp function returns a negative value if ch is smaller than "Y", or a positive value if it is greater than "Y" and 0 if both strings are equal.

There are several issues you should correct concerning how you handle input with scanf . First always, always validate the number of successful conversions you expect by checking the return for scanf . Next, as mentioned in the comment, there is NO need to include <string.h> in your code to make a one-letter comparison. Use a character comparison instead of a string comparison. Lastly, always limit your input to the number of characters available (plus the nul-terminating character.

Putting the bits together, you could do something like the following:

#include <stdio.h>

#define MAXN 100

int main (void) {

    char first_name[MAXN] = "", surname[MAXN] = "";
    int ch;

    printf ("What's your first name?: ");
    if (scanf ("%99[^\n]%*c", first_name) != 1) {
        fprintf (stderr, "error: invalid input - first name.\n");
        return 1;
    }
    printf ("Hey %s!\n", first_name);

    printf("Enter surname name? optional (Y/N) ");
    if (scanf("%c%*c", (char *)&ch) != 1) {
        fprintf (stderr, "error: invalid input - Y/N\n");
        return 1;
    }

    if (ch != 'y' && ch != 'Y')     /* handle upper/lower case response */
        return 1;

    printf ("Enter your surname?: ");
    if (scanf (" %99[^\n]%*c", surname) != 1) {
        fprintf (stderr, "error: invalid input - surname\n");
        return 1;
    }

    printf ("\nYour whole name is : %s %s\n", first_name, surname);

    return 0;
}

Example Use/Output

$ ./bin/firstlast
What's your first name?: David
Hey David!
Enter surname name? optional (Y/N) Y
Enter your surname?: Rankin

Your whole name is : David Rankin

Look it over and let me know if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM