C编程:仅从fgets打印int [英] C programming: print only int from fgets
本文介绍了C编程:仅从fgets打印int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
查看此main
:
int main(void)
{
int i;
int ch;
char str[512];
fgets(str, sizeof str, stdin);
for (i = 0; i <= (strlen(str)); i++)
{
if (str[i] != '\0' && str[i] != '\n')
{
int num = atoi(&str[i]);
printf("%d\n", num);
}
}
return 0;
}
我希望与用户的数字保持一致,并获取所有没有任何spaces
或tabs
的数字.
I want to get line with numbers from user and get all the numbers without any spaces
or tabs
.
例如:
输入1 2 3
.
但是在这种情况下,输出为:
The input 1 2 3
.
But in this case this the output:
1
2
2
3
3
那为什么我两次收到2
和3
?
So why i received 2
and 3
twice?
推荐答案
这是我的处理方式:
char line[256];
if (fgets(line, sizeof line, stdin) != NULL)
{
const char *ptr = line;
while (*ptr != '\0')
{
char *eptr = NULL;
const long value = strtol(ptr, &eptr, 10);
if (eptr != ptr)
printf("%ld\n", value);
else
break;
ptr = eptr;
}
}
这使用 strtol()
,因此它还将处理负数;如果这是不正确的,您当然可以添加检查以将其过滤掉.我认为这比使用strtok()
的任何方法都要好.
This uses strtol()
so it will also handle negative numbers; if this is incorrect you can of course add checks to filter them out. I think this is way better than anything using strtok()
.
这篇关于C编程:仅从fgets打印int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文