c - 使用 atoi 填充整数数组

标签 c arrays atoi

第一次在这里提问。抱歉,如果已经有关于此的线程,但我进行了一些搜索,但没有完全找到我认为我正在寻找的东西。我是 C 的新手,正在为我的微 Controller 系统类(class)做一些家庭作业练习。在我们进入嵌入式 C 之前,我们目前正在做一些简单的练习,我正在尝试编写一个程序,该程序将采用一行由 10 个数字组成的文本,这些数字用逗号分隔,并填充一个 int 随它。作为提示,我们被告知使用 substringatoi。我想我已经接近正确了,但我无法正确输出我的数字。

我也不是在寻找填鸭式的答案。现在一些提示就足够了。在寻求解决方案之前,我想尝试自己弄清楚。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int a[10];
    char str[] = {1,2,3,4,5,6,7,8,9,10}; //contains string of numbers
    int i;
    puts("This prints out ten numbers:");

    for (i = 0; i < 10; i++)
    {
        a[i] = atoi(str);
        printf("%d", a[i]);
            //i'm guessing the problem lies in one of the above two lines
    }
    return 0;
}

输出如下:

This prints out ten numbers:
0000000000

感谢任何可以提供帮助的人! 克里斯

最佳答案

您说您必须使用以逗号分隔的一行文本,但您实际上声明了一个包含十个(二进制)整数的 char 数组。要将其转换为字符串,您只需执行以下操作:

char str[] = "1,2,3,4,5,6,7,8,9,10";

然后您需要以某种方式处理此字符串,以将每个数字取出并放入您的 int 数组中。

关于c - 使用 atoi 填充整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283473/

相关文章:

c - 为链表数组分配内存

ios - 无法将类型 'Option' 的值转换为预期的参数类型 '@noescape (Option) throws -> Bool'

java - Arrays$ArrayList 无法在 java 中转换为 java.util.ArrayList

java - 2D int 数组洗牌

c - 使用 Eclipse 在 C 中将参数传递给 main

c - 将前导零添加到整数不起作用(arduino,c)

c - 如何在不限制堆栈的情况下限制使用 `malloc()` 获取的内存?

c++ - 如何修复 "no matching function for call to ' atoi'"错误?

c++ - 将字符串 vector 转换为 int

c - GLib宏g_slice_new问题