简体   繁体   中英

How do I get the user to input a word for string comparison?

I'm running a while loop so the user can constantly enter expressions , until they indicate they want to quit the program. I'm using strcmp() to compare two strings so as soon as they enter quit the program will stop. But the program keeps going, any Ideas?

#include <stdio.h>
#include <string.h>
int main()
{
    int min12=0;
    char opper;
    int x=0;
    int min13;
    char *Repeatprog="cont";
    char *Repeatprog1="quit";

    while (strcmp(Repeatprog,Repeatprog1))
    {
    printf("enter the integer number \n");
    scanf( "%d %c %d", &min12, &opper, &min13);
    printf("%d %c %d\n", min12, opper, min13);

    printf("Type the word quit to end program\n");
    scanf("%s", Repeatprog);
    }
    printf("Good Bye");
    return 0;
}

Remember always that an Array is a Pointer to the first object of the array. And secondly, in your call to scanf() you only read a character. Not a whole string (represented by %s in C)

So in conclusion, your call to scanf() shouldn't have a pointer and should have a string instead of a character .

scanf("%s", Repeatprog);

or simply

gets (Repeatprog);

EDIT :

As the commenter @EOF said, gets() is not a good idea since it can lead to Undefined Behaviour . That's because the program can read more characters than it should have and lead to overflow, thus it isn't secure.

So I recommend using char *fgets(char *str, int n, FILE *stream)

Note:

Also, your code is using string literals. So if you make any attempt to change the content of the char pointer then it will lead to Undefined Behaviour .

For this note, please thank the guys below me [comments]. I made a huge mistake and I'm sorry.

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