c - 如何在循环中使用 sscanf 处理错误以从标准输入获取输入?
问题描述
我正在编写一个代码来从键盘(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 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
,它就不会像 -1 那样工作。scanResult
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 ( pointer < end && (2 == sscanf(pointer, " ( %d , %d ) %n", &key, &value, &offset)) )
推荐阅读
- java - 错误:使用包含匕首生成源的 Gradle 编译 Java 项目时出现重复类
- python - 如何有效地检查数据库中是否存在名称
- c# - 创建仅负责创建其他对象(即工厂)的类时的最佳实践?
- python - 从 Mongo 获取 dict 并使用 Numpy 转换为 ndarray
- javascript - 使用素材箱放大动态显示的图像
- c# - 使用 .GetHashCode() 的对象相等列表
- php - 使用点符号访问多维数组的深度和多值
- python - 如何检查括号是否在python3中的一行打开并在另一行关闭?
- jquery - 根据选中的复选框显示来自数据库的结果
- wmi - 如何在 wmi_exporter 中配置多个查询?