所以我的程序必须从用户输入中读取2个整数并打印它们。我使用scanf,程序将退出错误的输入。但是,当输入为"3+2“或"3-2”时,scanf会忽略"+“和"-”符号,并将3和2读取为两个整数输入。我希望3+2和3-2作为错误的输入,程序将退出。我怎么才能修复它?
int num1, num2;
if (scanf("%d%d", &num1, &num2) != 2) {
//bad input, exit the program
}
else {
//print the two integers发布于 2014-01-24 11:06:52
你必须自己验证这个字符串。请考虑以下几点:
#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;
}逻辑如下:
发布于 2014-01-24 11:51:45
由于输入行中的两个数字之间似乎至少需要一个空格字符,因此代码需要如下所示:
char s[2];
if (scanf("%d%1[ \t]%d", &num1, s, &num) != 3)
...format error...这个(%1[ \t])查找紧跟在第一个数字后面的空格或制表符。在第二个数字之前可能有额外的空格。除非您愿意,否则不必对s中的值做任何操作。
(已修复以响应来自的准确 )
发布于 2014-01-24 14:29:10
使用"%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
}另一种方法,类似于@Jonathan Leffler,只接受至少1个空格
if (scanf("%d%*[ ]%d", &num1, &num2) != 2) {
; // bad input, exit the program
}同意其他许多说法:使用fgets()/sscanf()要好得多。
https://stackoverflow.com/questions/21323253
复制相似问题