gpt4 book ai didi

C编程: print only int from fgets

转载 作者:太空狗 更新时间:2023-10-29 17:01:22 24 4
gpt4 key购买 nike

查看此主要:

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;
}

我想从用户那里获取数字并获取所有没有任何 spacestabs 的数字。

例如:

输入 1 2 3。但在这种情况下,这是输出:

1
2
2
3
3

那么为什么我收到两次 23

最佳答案

这是我的做法:

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() 的任何方法都要好。

关于C编程: print only int from fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com