简体   繁体   English

如何让用户输入一个单词进行字符串比较?

[英]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.我正在运行一个 while 循环,以便用户可以不断输入表达式,直到他们表示要退出程序。 I'm using strcmp() to compare two strings so as soon as they enter quit the program will stop.我正在使用strcmp()来比较两个字符串,因此一旦它们进入quit程序就会停止。 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.其次,在您调用scanf()您只读取了一个字符。 Not a whole string (represented by %s in C)不是一个完整的字符串(在 C 中用%s表示)

So in conclusion, your call to scanf() shouldn't have a pointer and should have a string instead of a character .所以总而言之,您对scanf()调用不应该有一个指针,应该有一个string而不是一个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 .正如评论者@EOF 所说, gets()不是一个好主意,因为它会导致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)所以我推荐使用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 .因此,如果您尝试更改char指针的内容,则会导致Undefined Behaviour

For this note, please thank the guys below me [comments].对于这个笔记,请感谢我下面的人[评论]。 I made a huge mistake and I'm sorry.我犯了一个巨大的错误,我很抱歉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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