c - 如何在for循环中连接字符串?

标签 c arrays printf string-concatenation

我正在使用 C 语言的循环并尝试确定 fprintf 的工作原理。

fprintf(out, "%02X", (int)(ch & 0x00FF); 

此语句为循环的每次迭代打印出一个十六进制值字符。

我可以将其存储在变量或字符数组中吗?

如何将其连接成一个大字符串,然后将其写入文件?

我是否必须检查迭代的总大小,并在开始时将 char 数组设置为循环的正确大小,然后附加到此?

最佳答案

也许这会有所帮助。

程序需要多个十进制输入(最多 50 个)。它打印相应的十六进制值并将字符附加到字符串(以零结尾的字符数组)。最后,它打印字符串。

#include <stdio.h>

int main(void) {
    const int N = 50;
    int i = 0;
    char text[N+1];  // Make an array to hold the string
    text[0] = '\0';  // Zero terminate it
    int ch;

    while(i < N)
    {
        if (scanf("%d", &ch) != 1)  // Read decimal from stdin
        {
            break;                  // Break out if no decimal was returned
        }
        printf("%02X ", (ch & 0x00FF));

        text[i] = (ch & 0x00FF);  // Add the new char
        text[i+1] = '\0';         // Add a new string termination
        ++i;

    }
    printf("\n");

    printf("%s\n", text);
    return 0;
}

输入:

65 66 67 68

输出:

41 42 43 44

ABCD

或者这个替代方案,逐个字符地读取字符串,直到看到换行符:

#include <stdio.h>

int main(void) {
    const int N = 50;
    int i = 0;
    char text[N+1];
    text[0] = '\0';
    char ch;

    while(i <= N)
    {
        if (scanf("%c", &ch) != 1 || ch == '\n')
        {
            break;
        }
        printf("%02X ", ch);
        text[i] = ch;
        text[i+1] = '\0';
        ++i;
    }
    printf("\n");

    printf("%s\n", text);
    return 0;
}

输入:

编码很有趣

输出:

63 6F 64 69 6E 67 20 69 73 20 66 75 6E

编码很有趣

关于c - 如何在for循环中连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39454840/

相关文章:

c - DOS 中的非交互式驱动器列表

c - 如何通过环绕将 4 字节数组移位所有 32 位?

c - 引用的库函数不调用会被链接吗?

c - 通过snprintf将uint8_t/uint16_t数据类型转换为char[]

c - Valgrind:在 C 中释放链接列表时,大小 8 的读取无效

java - 如何检查 char 是否为某个字符

java - 为什么初始化数组后我无法在数组中分配某些值?

c - 为什么当我将 printf 与 %s 和 %c 一起使用时,打印的字符会发生变化?

c - 在控制台上写入和在 C 中写入文件时的输出差异

c++ - wchar_t 指针