简体   繁体   English

如何基于用户在C中的输入来停止程序

[英]How to stop a program based on user's input in C

I'm just starting to learn C and I'm having problem with stopping my program based on what the user inputted. 我刚刚开始学习C,并且在基于用户输入的内容停止程序方面遇到问题。

#include <stdio.h>
#include <stdbool.h>
int main()
{
int a;
int b;
char c[5];
printf("Enter the two values you like to compare, type stop to end.\n");
while (c != "stop")
{
    scanf_s(" %d %d %s", &a, &b, &c);
    if (!(a^b))
    {
        printf("both are equal\n");
        getchar();
    }
    else
    {
        printf("both are not equal\n");
        getchar();
    }
}
printf("Thanks for playing.");
getchar();
return 0;   
} 

The problem that I'm having is having to put in another variable, c, in my scanf_s. 我遇到的问题是必须在我的scanf_s中放入另一个变量c。 How would I do it so that the user does not have to put in another word after the 2 numbers? 我该怎么做,以使用户不必在两个数字后面输入另一个单词? Also how can I check if the user only input "stop" so that it will stop the program? 另外,如何检查用户是否仅输入“停止”以停止程序? Btw the way I have it right now also does not stop the program when I do "10 10 stop". 顺便说一句,当我执行“ 10 10 stop”时,我现在拥有的方法也不会停止程序。 Thanks. 谢谢。

  1. remove & for c in scanf_s(" %d %d %s", &a, &b, &c); 在scanf_s(“%d%d%s”,&a,&b,&c)中删除&for c;
  2. use strcmp to compare strings. 使用strcmp比较字符串。
  3. if you need to ignore case while comparing use strcasecmp (for UNIX based systems) and stricmp (for windows). 如果在比较时需要忽略大小写,请使用strcasecmp(对于基于UNIX的系统)和stricmp(对于Windows)。
  4. Use do-while instead of while if you need to run the loop at least once. 如果您需要至少运行一次循环,请使用do-while而不是while。

Full Working Code: 完整的工作代码:

#include <stdio.h>
#include <string.h>
int main()
{
  int a;
  int b;
  char c[5] = {'\0'};

  do {
    printf("Enter the two values you like to compare, type stop to end.\n");
    scanf("%d%d%s", &a, &b, c);
    if (!(a^b))
      {
    printf("both are equal\n");
    getchar();
      }
    else
      {
    printf("both are not equal\n");
    getchar();
      }
  }
  while (strcmp(c,"stop"));
  printf("Thanks for playing.");
  getchar();
  return 0;   
}

while (c != "stop")

You cannot compare strings in C like that, use memcmp() or strncmp() library functions available in string.h . 您不能像这样在C语言中比较strings ,请使用string.h可用的memcmp()strncmp()库函数。 Read about them to know how they can be implemented as condition in while loop. 阅读有关它们的信息,以了解如何将它们实现为while循环中的条件。

Also, to get string input, use 另外,要获取字符串输入,请使用
scanf_s(" %d %d %s", &a, &b, c); // Remove that litle '&' before 'c'.

NOTE: The function scanf_s returns the number of inputs scanned correctly, you should check that before proceeding with input values. 注意:函数scanf_s返回正确扫描的输入数,在继续输入值之前,您应该检查一下。

To get the user to stop without explicitly entering "stop", many ways are there: 为了使用户在不显式输入“停止”的情况下停止,有很多方法:

1) Use do-while loop and keep asking user if he wants to play more. 1)使用do-while循环并不断询问用户是否想玩更多游戏。
2) Use negative numbers input (say -1 ) to quit. 2)使用负数输入(例如-1 )退出。

Use line below to make sure your 'c' scan your string entered. 使用下面的行以确保您的'c'扫描输入的字符串。

scanf(" %d %d %s", &a, &b, c); scanf(“%d%d%s”,&a,&b,c);

Edit: Consider replacing your while with line below to make sure you stop works. 编辑:考虑将您的while替换为下面的行,以确保您停止工作。 Include "string.h" 包括“ string.h”

 while (strcmp(c,"stop")) 

Here is the fixed version... I have add the comments in the code for understanding... 这是固定版本...为了方便理解,我在代码中添加了注释...

#include <stdio.h>
#include <string.h>
int main()
{
    int a;
    int b;
    char c[5] = {'\0'};
    printf("Enter the two values you like to compare, type stop to end.\n");
    while (strcmp(c,"stop"))
    {
        scanf("%d%d%s", &a, &b, c);
        if (!(a^b))
        {
            printf("both are equal\n");
            getchar();
        }
        else
        {
            printf("both are not equal\n");
            getchar();
        }
    }
    printf("Thanks for playing.");
    getchar();
    return 0;   
} 

Its because you are using &c instead of just c in scanf_s . 这是因为您使用的是&c而不是scanf_s c Replace that and it should work. 替换它,它应该工作。 Also, c is a string , so, you have to use strcmp instead of != . 另外, c是一个string ,因此,您必须使用strcmp而不是!=

An easier way to write this code would be:: 编写此代码的一种更简单的方法是:

int main()
{
int a;
int b;
char c;
do
{
    printf("Would you like to play?\nPress 'Y' for 'Yes' or 'N' for 'No'\n");
    scanf( "%c", &c ) ;
    /*scanf_s( "%c", &c, 1 ) ; */
    if( c != 'Y' && c != 'y' )
        break ;

    printf("Enter the two values you like to compare\n" ) ;
    scanf(" %d %d", &a, &b);
    if (!(a^b))
    {
        printf("both are equal\n");
        getchar();
    }
    else
    {
        printf("both are not equal\n");
        getchar();
    }
}while(1) ;
printf("Thanks for playing.");
getchar();
return 0;   
} 

First, lets correct your program: &c (third argument to scanf_s) is incorrect. 首先,让我们更正您的程序: &c (scanf_s的第三个参数)不正确。 It should be c (because it is already a pointer). 它应该是c (因为它已经是一个指针)。 According to docs, scanf_s requires sizes to be specified for all %s format strings; 根据文档, scanf_s 要求为所有%s格式字符串指定大小 therefore, the way you are doing things now, you should have written scanf_s(" %d %d %4s", &a, &b, c); 因此,按照现在的操作方式,您应该已经编写了scanf_s(" %d %d %4s", &a, &b, c);

The program would be much easier to use if you changed your logic to "enter a blank line to exit". 如果您将逻辑更改为“输入空白行以退出”,则该程序将更易于使用。 You can test this looking at the return value of scanf_s , which will be the number of format strings correctly read from the input. 您可以查看scanf_s的返回值来进行测试,该返回值将是从输入中正确读取的格式字符串的数量。

If you need to ask for strings, then allow either, and look at whatever the user wrote to see whether it was number or string: 如果您需要输入字符串,则允许其中一个,然后查看用户写的内容以查看它是数字还是字符串:

#include <stdio.h>
#include <string.h> 

int main()  {
    int a;
    int b;
    char c[32];
    printf("Enter the two values to compare, or type stop to end.\n");
    while (fgets(c, 31, stdin) != NULL && strncmp("stop\n", c)) != 0) {

        // user did not request to exit and wrote something; maybe 2 numbers
        if (sscanf(c, "%d %d", &a, &b) != 2) {
            // but he did not write two numbers. Complain and repeat.
            printf("please write two numbers to compare, or type stop to end.\n");
            continue; 
        }

        if (a == b) {
            printf("both are equal\n");
        } else  {
            printf("both are not equal\n");
        }
    }
    printf("Thanks for playing.\n");
    return 0;   
} 

fgets reads whole lines, and you can then try to parse them using sscanf . fgets读取整行,然后您可以尝试使用sscanf解析它们。 This has the advantage over common scanf that you can try to parse the same line in different ways, depending on what you find in it. 与普通scanf相比,它的优势在于您可以尝试根据自己在其中找到的内容以不同的方式解析同一行。 Generally, you do not want to fill your code with getchar() . 一般情况下,你不想来填补你的代码getchar() If you are debugging, your debugger will stop for you. 如果要调试,调试器将为您停止。 If you are not debugging, you will want to test or use your program with input redirection , and getchar() is simply not needed. 如果您不进行调试,则需要通过输入重定向来测试或使用程序,而根本不需要getchar()

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

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