我正在从文件中读取数据,我只需要从以下数据中提取整数。我该如何完成它?谢谢。
我的输入将是 field6,我需要删除这些字符“];” 并将其存储在一个整数变量中。
我的代码:-
field6 = strtok(NULL," ");
if (isdigit(field6))
{
weight = atoi (field6);
printf("%d\n",weight);
}
输入:
43];
2];
4];
16];
25];
输出:
43
2
4
16
25
尝试
field6 = strtok(NULL,"\n");
weight = atoi (field6);
printf("%d\n",weight);
这是 atoi 完全按照您的需要做的那些罕见的情况之一。
无法检测到的错误条件是“];” 那将被解释为零。
没有 sscanf 然后:
#include <stdio.h>
int main(int argc, char** argv)
{
const char *test = "123];";
int i = 0;
const char *p = test;
while (*p && isdigit(*p))
{
if (p != test) i *= 10;
i += *p - '0';
++p;
}
if (*p != ']')
{
// we have an error!
return 1;
}
printf("%i\n", i);
}