c - 如何拆分 unsigned char 数组中的元素

标签 c arrays

我有以下内容:

unsigned char input[];
unsigned char *text = &input[];

我正在接受用户输入,如下所示:

do {
    printf ("Please enter an numeric message terminated by -1:\n");
    fgets(input, sizeof(input), stdin);
}
while (input[0] == '\n')

由于我的输出将为我提供一系列单个字符,因此如何 我可以把它们连接起来吗?如果我输入以下内容:

14 156 23 72 122

当我尝试使用它时,它会将其分解为:

1 4 1 5 6 ...

换句话说,当我想将它作为无符号字符传递给函数时, 我想传递'14',这样函数就可以读取14的二进制,而不是 1,然后 4,等等。任何帮助将不胜感激!

最佳答案

就目前情况而言,您的代码无法编译。

您不能像这样声明这些变量:

unsigned char input[]; 
unsigned char *text = &input[];

您需要说明输入应该有多大。我不确定您对第二个定义做了什么。

您还需要在此行后面添加分号

while (input[0] == '\n')
<小时/>

除此之外,如果输入由已知分隔符分隔,您可以使用 strtok() 而不是逐字节读取字符串。

我废弃了你的程序,因为它没有编译。这就是我假设您正在尝试对代码执行的操作,请相应地进行调整:

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

/*
 * Converts "input" separated by "delims" to an array of "numbers"
 */
size_t str_to_nums(const char* input, const char* delims, int* numbers, size_t numsize)
{
    char* parsed = malloc(strlen(input) + 1); /* allocate memory for a string to tokenize */
    char* tok; /* the current token */
    size_t curr; /* the current index in the numbers array */

    strcpy(parsed, input); /* copy the string so we don't modify the original */

    curr = 0;
    tok = strtok(parsed, delims);

    while(tok != NULL && curr < numsize) { /* tokenize until NULL or we exceed the buffer size */
        numbers[curr++] = atoi(tok); /* convert token to integer */
        tok = strtok(NULL, delims); /* get the next token */
    }

    free(parsed);

    return curr; /* return the number of tokens parsed */
}

int main(void)
{
    char input[256];
    int numbers[64];
    size_t count, i;

    puts("Please enter an numeric message terminated by -1:");
    fgets(input, sizeof(input), stdin);

    count = str_to_nums(input, " ", numbers, sizeof(numbers)/sizeof(*numbers)); /* string is separated by space */

    for(i = 0; i < count; ++i) {
        printf("%d\n", numbers[i]); /* show the results */
    }
}

P.s.这不是串联。您要查找的短语是“字符串拆分”或“标记化”。

关于c - 如何拆分 unsigned char 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33028653/

相关文章:

c - Freertos + STM32F2 - 将堆栈分配给线程后总堆大小错误

c - 为什么我的C程序无法正确计算和打印文本文件中的整数?

c++ - 用于测试 C/C++ 语法的示例

javascript - 使数组上的值匹配更快?

java - 在不创建新副本的情况下获取数组的一部分

c - GCC 如何阻止程序内的系统调用?

iphone - Objective C 改变一个对象的值

php - 减去数组值

javascript - 在javascript中将字符串转换为数组内的整数

javascript - 通过对象键将数组项移到前面