简体   繁体   English

从c中的用户输入读取2个整数

[英]Read 2 integers from user input in c

So my program has to read 2 integers from user input and print them. 因此,我的程序必须从用户输入中读取2个整数并将其打印出来。 I use scanf, and the program will exit on bad input. 我使用scanf,该程序将在输入错误时退出。 However, when the input is "3+2" or "3-2", scanf ignores the "+" and "-" signs and reads 3 and 2 as two integer inputs. 但是,当输入为“ 3 + 2”或“ 3-2”时,scanf会忽略“ +”和“-”符号,并将3和2读取为两个整数输入。 I want 3+2 and 3-2 as bad inputs, and the program will exit. 我希望3 + 2和3-2作为错误的输入,程序将退出。 How can I fix it? 我该如何解决?

int num1, num2;
if (scanf("%d%d", &num1, &num2) != 2) {
        //bad input, exit the program
    }
    else {
        //print the two integers

You'll have to validate the string yourself. 您必须自己验证字符串。 Consider the following: 考虑以下:

#include <stdio.h>
#include <ctype.h>

#define MAX_STR_LEN (50)

int main(void)
{
    char str[MAX_STR_LEN] = {0};
    int num1, num2;

    printf("Enter two numbers: ");
    fgets(str, MAX_STR_LEN, stdin);

    for(int i = 0; i < MAX_STR_LEN; i++)
    {
        if(!isdigit(str[i]) && (!isspace(str[i])) && (str[i] != '\0'))
        {
            if((i != 0) && (str[i - 1] != ' ') && ((str[i] != '+') || (str[i] != '-')))
            {
                printf("'%c' is bogus! I'm self destructing!", str[i]);
                return -1;
            }
        }

        if((str[i] == '\n') || (str[i] == '\0'))
            break;
    }

    sscanf(str, "%d%d", &num1, &num2);
    printf("You entered %d and %d. Good job.  Pat yourself on the back.", num1, num2);

    return 0;
}

The logic is as follows: 逻辑如下:

  1. Read user input as a generic string. 读取用户输入作为通用字符串。
  2. Search string for offending characters or character sequences. 在字符串中搜索有问题的字符或字符序列。
  3. If none, parse string accordingly. 如果没有,则相应地解析字符串。
  4. Sit back and gloat. 坐下来,幸灾乐祸。

Since the requirement seems to be at least one space character between the two numbers in the input line, the code will need to be something like: 由于要求似乎是输入行中两个数字之间至少有一个空格字符,因此代码将需要像这样:

char s[2];
if (scanf("%d%1[ \t]%d", &num1, s, &num) != 3)
    ...format error...

This ( %1[ \\t] ) looks for a blank or tab immediately after the first number. 此( %1[ \\t] )在第一个数字后立即查找空白或制表符。 There could be extra blanks before the second number. 第二个数字之前可能会有多余的空格。 You don't have to do anything with the value in s unless you want to. 除非您愿意,否则您无需对s的值做任何事情。

( Fixed in response to an accurate comment from chux ) 修正为回应chux的准确评论

Scan using "%n" to detect a separating white-space. 使用"%n"进行扫描以检测分隔的空格。

int num1, num2;
int n1, n2;
if (scanf("%d%n %n%d", &num1, &n1, &n2, &num2) != 2) {
  ; // bad input, exit the program
}
if (n1 == n2) {
  ; // no space between 1st and 2nd number, exit the program
}

Another approach, similar to @Jonathan Leffler, only accepts at least 1 space 类似于@Jonathan Leffler的另一种方法,仅接受至少一个空格

if (scanf("%d%*[ ]%d", &num1, &num2) != 2) {
  ; // bad input, exit the program
}

Agree with many other say: Using the fgets()/sscanf() is much better. 同意很多其他说法:使用fgets()/sscanf()更好。

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

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