如何在循环中使用sscanf处理错误,以从stdin获取输入?
我正在编写一个代码,从键盘(stdin)读取输入并打印它们。标准输入如下所示如何在循环中使用sscanf处理错误,以从stdin获取输入?,c,error-handling,while-loop,scanf,stdin,C,Error Handling,While Loop,Scanf,Stdin,我正在编写一个代码,从键盘(stdin)读取输入并打印它们。标准输入如下所示 (6, 10) (6, 12) (6, 20) (6, 25) (9, 25) (10,25) 代码如下: void main() { int key, value; char input[1000]; //assume the input is than 1000 bits and initiate the inputs as strings char *pointer; int
(6, 10) (6, 12) (6, 20) (6, 25) (9, 25) (10,25)
代码如下:
void main()
{
int key, value;
char input[1000]; //assume the input is than 1000 bits and initiate the inputs as strings
char *pointer;
int offset;
printf("enter key-value pairs of integer numbers like (a,b)(c,d): ");
fgets(input, sizeof(input), stdin);
pointer = input;
//read the pairs of values one at a time until the last pair
// leave space before and after value and brackets to skip spaces
while (sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset) == 2)
{
printf("key is %d, value is %d", key, value);
pointer = pointer + offset
}
}
我还想改进错误处理的代码。例如,如果用户输入如下:
(6, 10) (6, 12) (6, ABC) (DEF, 25) (9, 25) (10,25)
我尝试在while循环完成后添加一个scanResult
,很明显,当扫描完最后一对值后,scanResult
将为-1,因此它将无法工作
void main()
{
int key, value;
char input[1000]; //assume the input is than 1000 bits and initiate the inputs as strings
char *pointer;
int offset;
int scanResult;
printf("enter key-value pairs of integer numbers like (a,b)(c,d): ");
fgets(input, sizeof(input), stdin);
pointer = input;
//read the pairs of values one at a time until the last pair
// leave space before and after value and brackets to skip spaces
while ((scanResult = sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset)) == 2)
{
printf("key is %d, value is %d", key, value);
pointer = pointer + offset
}
if (scanfResult != 2)
{
printf("invalid input");
}
return;
}
有人能告诉我如何编写错误处理代码吗?您可以执行以下操作:
char *end = input + strlen(input);
及
while(指针
为scanfResult==EOF
添加检查?如if(scanResult!=EOF&&scanResult!=2)
?
while ( pointer < end && (2 == sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset)) )