作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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/
我是一名优秀的程序员,十分优秀!