简体   繁体   English

使用 if 语句检测用户是否输入了特定字符或数字

[英]Use if statement to detect if user entered specific character or number

In my getInput function I am scanning input from the user.在我的 getInput 函数中,我正在扫描来自用户的输入。

If the user enters 'q' or 'Q' I want to print that the user wishes to exit (the program doesn't have to actually 'exit' in technical terms).如果用户输入'q''Q'我想打印用户希望退出的信息(从技术角度讲,程序实际上不必“退出”)。

If the user enters any other value, I want to return that value and continue running my program.如果用户输入任何其他值,我想返回该值并继续运行我的程序。

So, my question is:所以,我的问题是:

How can I test for a certain character value int-to-char conversion similar to how I've attempted it below?我如何测试某个字符值 int-to-char 转换类似于我在下面尝试的方式?

My program exits if the user enters a character and runs if the user enters an integer, but doesn't properly detect that 'q' or 'Q' has been pressed.如果用户输入一个字符,我的程序会退出,如果用户输入一个整数,我的程序就会运行,但没有正确检测到'q''Q'已被按下。

This is the code I have so far:这是我到目前为止的代码:

int getInput() {

  int numSets;
  char quitTest1 = 'q';
  char quitTest2 = 'Q';

  //get number of sets from user
  printf("\nEnter desired amount of random number sets (or 'q'/'Q' to quit): ");
  scanf("%d", &numSets);

  if (numSets == (int)quitTest1 || numSets == (int)quitTest2) {
    printf("Exited");
  }

  else {
    return numSets;
  }

}

I'm probably missing some major principle but I can't seem to find much help on Google.我可能遗漏了一些主要原则,但我似乎在 Google 上找不到太多帮助。

All answers are appreciated.所有的答案都表示赞赏。

Note that注意

scanf("%d", &numSets);

Will not assign any value to numSets if input is a character, numSets will maintain its previous value, which in this case is unknown since the variable is uninitialized, using it ahead will cause undefined behaviour.如果 input 是字符, numSets不会为numSets分配任何值, numSets将保持其先前的值,在这种情况下,由于变量未初始化,因此该值未知,提前使用它会导致未定义的行为。

Getting the input as a char array an convert to char or int seems the best option.将输入作为char array转换为charint似乎是最好的选择。

Live sample here现场样品在这里

int getInput() {

    char numSets[100];
    int number = -1;
    char q;
    char quitTest1 = 'q';
    char quitTest2 = 'Q';

    //get number of sets from user
    printf("\nEnter desired amount of random number sets (or 'q'/'Q' to quit): ");
    fgets(numSets, sizeof(numSets), stdin);
    if (sscanf(numSets, "%d", &number)){
        printf("%d", number); //testing
        return number;
    } 

    if (sscanf(numSets, "%c", &q) && (q == quitTest1 || q == quitTest2))
        printf("Exited");
    else{
        puts("Invalid input");

    return number; //will return -1;
}

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

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