gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:57:34 24 4
gpt4 key购买 nike

我正在使用 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/

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