use*_*206 8 c string loops spaces atoi
看到这个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;
}
Run Code Online (Sandbox Code Playgroud)
我希望得到来自用户的数字并获得所有数字,而不是任何spaces或tabs.
例如:
输入1 2 3.但在这种情况下这输出:
1
2
2
3
3
Run Code Online (Sandbox Code Playgroud)
那么,为什么我收到2并3两次?
我是这样做的:
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;
    }
}
Run Code Online (Sandbox Code Playgroud)
这样使用strtol()它也会处理负数; 如果这是不正确的,你当然可以添加检查来过滤它们.我认为这比使用任何东西都要好strtok().
因为你也传递了以空格开头的字符串的位置.他们得到第一个数字2,3分别得到两次.这就是返回的内容.
for (i = 0; i <= (strlen(str)); i++)
{
    if (str[i] != '\0' && !isspace(str[i]) )
    {
        int num = atoi(&str[i]);
        printf("%d\n", num);
    }
}
Run Code Online (Sandbox Code Playgroud)
打印:
1
2
3
Run Code Online (Sandbox Code Playgroud)
出于标记化的目的,您可以使用strtok和将其转换为数字strtol等.这些可以更好地控制错误情况atol/atoi.